Skip to content

A local-first personal finance app

[AI] Persist custom CSS override across theme changes (#7495)

Matiss Janis Aboltins4b940423eef7
diff --git a/packages/desktop-client/src/components/settings/ThemeInstaller.test.tsx b/packages/desktop-client/src/components/settings/ThemeInstaller.test.tsx
index 9eab34240f..004eac41be 100644
--- a/packages/desktop-client/src/components/settings/ThemeInstaller.test.tsx
+++ b/packages/desktop-client/src/components/settings/ThemeInstaller.test.tsx
@@ -1,8 +1,9 @@
-import { render, screen, waitFor } from '@testing-library/react';
+import { render as rtlRender, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useThemeCatalog } from '#hooks/useThemeCatalog';
+import { resetTestProviders, TestProviders } from '#mocks';
import {
fetchThemeCss,
generateThemeId,
@@ -11,6 +12,9 @@ import {
import { ThemeInstaller } from './ThemeInstaller';
+const render: typeof rtlRender = (ui, options) =>
+ rtlRender(ui, { wrapper: TestProviders, ...options });
+
vi.mock('#style/customThemes', async () => {
const actual = await vi.importActual('#style/customThemes');
return {
@@ -34,6 +38,18 @@ vi.mock('#hooks/useThemeCatalog', () => ({
useThemeCatalog: vi.fn(),
}));
+const mockSetCustomCssOverride = vi.fn();
+let mockCustomCssOverride: string | undefined = undefined;
+
+vi.mock('#hooks/useGlobalPref', () => ({
+ useGlobalPref: (key: string) => {
+ if (key === 'customCssOverride') {
+ return [mockCustomCssOverride, mockSetCustomCssOverride];
+ }
+ return [undefined, vi.fn()];
+ },
+}));
+
describe('ThemeInstaller', () => {
const mockOnInstall = vi.fn();
const mockOnClose = vi.fn();
@@ -84,8 +100,11 @@ describe('ThemeInstaller', () => {
beforeEach(() => {
vi.clearAllMocks();
+ resetTestProviders();
mockOnInstall.mockClear();
mockOnClose.mockClear();
+ mockSetCustomCssOverride.mockClear();
+ mockCustomCssOverride = undefined;
vi.mocked(fetchThemeCss).mockResolvedValue(mockValidCss);
vi.mocked(validateThemeCss).mockImplementation(css => css.trim());
// Reset generateThemeId mock to default behavior
@@ -324,314 +343,146 @@ describe('ThemeInstaller', () => {
});
});
- describe('pasted CSS installation', () => {
- it('calls onInstall when valid CSS is pasted and Apply is clicked', async () => {
- const user = userEvent.setup();
- render(
- <ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
- );
-
- const textArea = screen.getByRole('textbox', {
- name: 'Custom Theme CSS',
- });
- await user.click(textArea);
- await user.paste(mockValidCss);
-
- const applyButton = screen.getByText('Apply');
- await user.click(applyButton);
-
- await waitFor(() => {
- expect(validateThemeCss).toHaveBeenCalledWith(mockValidCss);
- expect(mockOnInstall).toHaveBeenCalledTimes(1);
- expect(mockOnInstall).toHaveBeenCalledWith(
- expect.objectContaining({
- name: 'Custom Theme',
- repo: '',
- overrideCss: mockValidCss,
- }),
- );
- });
- });
-
- it('trims whitespace from pasted CSS before validation', async () => {
+ describe('close button', () => {
+ it('calls onClose when close button is clicked', async () => {
const user = userEvent.setup();
render(
<ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
- const textArea = screen.getByRole('textbox', {
- name: 'Custom Theme CSS',
- });
- const cssWithWhitespace = ` ${mockValidCss} `;
- await user.click(textArea);
- await user.paste(cssWithWhitespace);
-
- const applyButton = screen.getByText('Apply');
- await user.click(applyButton);
+ const closeButton = screen.getByText('Close');
+ await user.click(closeButton);
- expect(validateThemeCss).toHaveBeenCalledWith(cssWithWhitespace.trim());
+ expect(mockOnClose).toHaveBeenCalledTimes(1);
});
+ });
- it('calls onInstall with empty cssContent when Apply is clicked with empty CSS', async () => {
- const user = userEvent.setup();
+ describe('catalog theme display', () => {
+ it('displays theme color palette correctly', () => {
render(
<ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
- const applyButton = screen.getByText('Apply');
- expect(applyButton).not.toBeDisabled();
-
- await user.click(applyButton);
+ // Check that color palettes are rendered instead of images
+ const images = screen.queryAllByRole('img');
+ expect(images.length).toBe(0);
- await waitFor(() => {
- expect(mockOnInstall).toHaveBeenCalledTimes(1);
- expect(mockOnInstall).toHaveBeenCalledWith(
- expect.objectContaining({
- cssContent: '',
- }),
- );
+ // Check that color swatches are rendered (6 divs per theme)
+ const demoThemeButton = screen.getByRole('button', {
+ name: 'Demo Theme',
});
+ const colorSwatches = demoThemeButton.querySelectorAll('[data-swatch]');
+ expect(colorSwatches.length).toBe(6);
});
- it('calls onInstall with empty cssContent when Apply is clicked with whitespace-only CSS', async () => {
- const user = userEvent.setup();
+ it('displays theme author correctly', () => {
render(
<ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
- const textArea = screen.getByRole('textbox', {
- name: 'Custom Theme CSS',
- });
- await user.click(textArea);
- await user.paste(' ');
-
- const applyButton = screen.getByText('Apply');
- expect(applyButton).not.toBeDisabled();
-
- await user.click(applyButton);
-
- await waitFor(() => {
- expect(mockOnInstall).toHaveBeenCalledTimes(1);
- expect(mockOnInstall).toHaveBeenCalledWith(
- expect.objectContaining({
- cssContent: '',
- }),
- );
- });
- });
-
- it('populates text box with installed custom theme CSS when reopening', () => {
- const installedCustomTheme = {
- id: 'theme-abc123',
- name: 'Custom Theme',
- repo: '',
- cssContent: mockValidCss,
- };
-
- render(
- <ThemeInstaller
- onInstall={mockOnInstall}
- onClose={mockOnClose}
- installedTheme={installedCustomTheme}
- />,
- );
-
- const textArea = screen.getByRole('textbox', {
- name: 'Custom Theme CSS',
- });
- expect(textArea).toHaveValue(mockValidCss);
+ // Author should be displayed as "by actualbudget"
+ const authorTexts = screen.getAllByText(/by/i);
+ expect(authorTexts.length).toBeGreaterThan(0);
});
- it('does not populate text box when installed theme has a repo', () => {
- const installedCatalogTheme = {
- id: 'theme-xyz789',
- name: 'Demo Theme',
- repo: 'https://github.com/actualbudget/demo-theme',
- cssContent: mockValidCss,
- };
-
+ it('displays source link for themes', () => {
render(
- <ThemeInstaller
- onInstall={mockOnInstall}
- onClose={mockOnClose}
- installedTheme={installedCatalogTheme}
- />,
+ <ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
- const textArea = screen.getByRole('textbox', {
- name: 'Custom Theme CSS',
- });
- expect(textArea).toHaveValue('');
+ const sourceLinks = screen.getAllByText('Source');
+ expect(sourceLinks.length).toBeGreaterThan(0);
});
+ });
- it('clears selected catalog theme when CSS is pasted', async () => {
- const user = userEvent.setup();
+ describe('customCssOverride pref binding', () => {
+ it('pre-fills the textarea from customCssOverride on mount', () => {
+ mockCustomCssOverride = ':root { --color-accent: #ff00aa; }';
render(
<ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
-
- // First select a theme (which should be selected/highlighted)
- await user.click(screen.getByRole('button', { name: 'Demo Theme' }));
- await waitFor(() => {
- expect(fetchThemeCss).toHaveBeenCalled();
- });
-
- // Then paste CSS
- const textArea = screen.getByRole('textbox', {
- name: 'Custom Theme CSS',
- });
- await user.click(textArea);
- await user.paste(mockValidCss);
-
- // Selection should be cleared (we can't easily test visual state,
- // but the handler should clear it)
- expect(textArea).toHaveValue(mockValidCss);
+ expect(screen.getByLabelText('Custom Theme CSS')).toHaveValue(
+ ':root { --color-accent: #ff00aa; }',
+ );
});
- it('clears error when CSS is pasted', async () => {
- const user = userEvent.setup();
+ it('leaves the textarea empty when customCssOverride is undefined', () => {
+ mockCustomCssOverride = undefined;
render(
<ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
-
- // First create an error
- vi.mocked(fetchThemeCss).mockRejectedValueOnce(new Error('Test error'));
- await user.click(screen.getByRole('button', { name: 'Demo Theme' }));
- await waitFor(() => {
- expect(screen.getByText('Test error')).toBeInTheDocument();
- });
-
- // Then paste CSS
- const textArea = screen.getByRole('textbox', {
- name: 'Custom Theme CSS',
- });
- await user.click(textArea);
- await user.paste(mockValidCss);
-
- // Error should be cleared
- expect(screen.queryByText('Test error')).not.toBeInTheDocument();
+ expect(screen.getByLabelText('Custom Theme CSS')).toHaveValue('');
});
- });
- describe('error handling for pasted CSS', () => {
- it('displays error when validateThemeCss throws for pasted CSS', async () => {
+ it('writes validated CSS to customCssOverride when Apply is pressed', async () => {
const user = userEvent.setup();
- const validationError = 'Theme CSS must contain exactly :root';
- vi.mocked(validateThemeCss).mockImplementation(() => {
- throw new Error(validationError);
- });
+ mockCustomCssOverride = undefined;
+ vi.mocked(validateThemeCss).mockImplementation(css => css.trim());
render(
<ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
-
- const textArea = screen.getByRole('textbox', {
- name: 'Custom Theme CSS',
- });
- await user.click(textArea);
- await user.paste('invalid css');
-
- const applyButton = screen.getByText('Apply');
- await user.click(applyButton);
-
- await waitFor(() => {
- expect(screen.getByText(validationError)).toBeInTheDocument();
- });
-
- expect(mockOnInstall).not.toHaveBeenCalled();
+ const textarea = screen.getByLabelText('Custom Theme CSS');
+ await user.click(textarea);
+ await user.paste(' :root { --color-accent: #ff0000; } ');
+ await user.click(screen.getByRole('button', { name: 'Apply' }));
+
+ // validateThemeCss is mocked as css => css.trim(), so the setter
+ // must receive the trimmed version — not the raw pasted string.
+ // This proves the Apply path runs validation, not a raw pass-through.
+ expect(mockSetCustomCssOverride).toHaveBeenCalledWith(
+ ':root { --color-accent: #ff0000; }',
+ );
+ // Textarea must also reflect the normalized value so the editor stays
+ // in sync with what was actually persisted.
+ expect(textarea).toHaveValue(':root { --color-accent: #ff0000; }');
});
- });
- describe('loading states', () => {
- it('disables Apply button when loading', async () => {
+ it('clears customCssOverride when Apply is pressed with an empty textarea', async () => {
const user = userEvent.setup();
- vi.mocked(fetchThemeCss).mockImplementation(
- () =>
- new Promise(resolve => {
- setTimeout(() => resolve(mockValidCss), 100);
- }),
- );
+ mockCustomCssOverride = ':root { --color-accent: #ff0000; }';
render(
<ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
+ const textarea = screen.getByLabelText('Custom Theme CSS');
+ await user.clear(textarea);
+ await user.click(screen.getByRole('button', { name: 'Apply' }));
- await user.click(screen.getByRole('button', { name: 'Demo Theme' }));
-
- const applyButton = screen.getByText('Apply');
- expect(applyButton).toBeDisabled();
+ expect(mockSetCustomCssOverride).toHaveBeenCalledWith('');
});
- it('disables Apply button when pasted CSS is empty during loading', async () => {
+ it('shows an error and does not write when CSS is invalid', async () => {
const user = userEvent.setup();
- vi.mocked(fetchThemeCss).mockImplementation(
- () =>
- new Promise(resolve => {
- setTimeout(() => resolve(mockValidCss), 100);
- }),
- );
+ mockCustomCssOverride = undefined;
+ vi.mocked(validateThemeCss).mockImplementation(() => {
+ throw new Error('invalid css');
+ });
render(
<ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
+ const textarea = screen.getByLabelText('Custom Theme CSS');
+ await user.type(textarea, 'not valid css');
+ await user.click(screen.getByRole('button', { name: 'Apply' }));
- // Trigger loading state
- await user.click(screen.getByRole('button', { name: 'Demo Theme' }));
-
- const applyButton = screen.getByText('Apply');
- expect(applyButton).toBeDisabled();
+ expect(mockSetCustomCssOverride).not.toHaveBeenCalled();
+ expect(await screen.findByText('invalid css')).toBeInTheDocument();
});
- });
- describe('close button', () => {
- it('calls onClose when close button is clicked', async () => {
+ it('does not touch customCssOverride when clicking a catalog theme', async () => {
const user = userEvent.setup();
- render(
- <ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
- );
-
- const closeButton = screen.getByText('Close');
- await user.click(closeButton);
+ mockCustomCssOverride = ':root { --color-accent: #ff0000; }';
- expect(mockOnClose).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('catalog theme display', () => {
- it('displays theme color palette correctly', () => {
render(
<ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
);
+ await user.click(screen.getByRole('button', { name: 'Demo Theme' }));
- // Check that color palettes are rendered instead of images
- const images = screen.queryAllByRole('img');
- expect(images.length).toBe(0);
-
- // Check that color swatches are rendered (6 divs per theme)
- const demoThemeButton = screen.getByRole('button', {
- name: 'Demo Theme',
+ await waitFor(() => {
+ expect(mockOnInstall).toHaveBeenCalled();
});
- const colorSwatches = demoThemeButton.querySelectorAll('[data-swatch]');
- expect(colorSwatches.length).toBe(6);
- });
-
- it('displays theme author correctly', () => {
- render(
- <ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
- );
-
- // Author should be displayed as "by actualbudget"
- const authorTexts = screen.getAllByText(/by/i);
- expect(authorTexts.length).toBeGreaterThan(0);
- });
-
- it('displays source link for themes', () => {
- render(
- <ThemeInstaller onInstall={mockOnInstall} onClose={mockOnClose} />,
- );
-
- const sourceLinks = screen.getAllByText('Source');
- expect(sourceLinks.length).toBeGreaterThan(0);
+ expect(mockSetCustomCssOverride).not.toHaveBeenCalled();
});
});
});
diff --git a/packages/desktop-client/src/components/settings/ThemeInstaller.tsx b/packages/desktop-client/src/components/settings/ThemeInstaller.tsx
index 345004762f..3da290c225 100644
--- a/packages/desktop-client/src/components/settings/ThemeInstaller.tsx
+++ b/packages/desktop-client/src/components/settings/ThemeInstaller.tsx
@@ -14,6 +14,7 @@ import { View } from '@actual-app/components/view';
import { Link } from '#components/common/Link';
import { FixedSizeList } from '#components/FixedSizeList';
+import { useGlobalPref } from '#hooks/useGlobalPref';
import { useThemeCatalog } from '#hooks/useThemeCatalog';
import {
embedThemeFonts,
@@ -48,11 +49,12 @@ export function ThemeInstaller({
mode,
}: ThemeInstallerProps) {
const { t } = useTranslation();
+ const [customCssOverride, setCustomCssOverride] =
+ useGlobalPref('customCssOverride');
const [selectedCatalogTheme, setSelectedCatalogTheme] =
useState<CatalogTheme | null>(null);
const [erroringTheme, setErroringTheme] = useState<CatalogTheme | null>(null);
const [pastedCss, setPastedCss] = useState('');
- const [cachedCatalogCss, setCachedCatalogCss] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -63,20 +65,14 @@ export function ThemeInstaller({
error: catalogError,
} = useThemeCatalog();
- // Initialize state from installed theme
+ // Mount-only: pref changes while the installer is open should not clobber
+ // in-progress edits to the textarea.
useEffect(() => {
- if (!installedTheme) return;
-
- if (installedTheme.repo) {
- // Catalog theme installed — restore overrideCss into text area if present
- if (installedTheme.overrideCss) {
- setPastedCss(installedTheme.overrideCss);
- }
- } else {
- // Custom pasted CSS — restore into text area
- setPastedCss(installedTheme.cssContent);
+ if (customCssOverride) {
+ setPastedCss(customCssOverride);
}
- }, [installedTheme]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
// Calculate theme item width based on container width (always 3 per row)
const getItemWidth = useCallback((containerWidth: number) => {
@@ -111,7 +107,6 @@ export function ThemeInstaller({
errorMessage: string;
catalogTheme?: CatalogTheme | null;
baseTheme?: 'light' | 'dark' | 'midnight';
- overrideCss?: string;
}) => {
setError(null);
setErroringTheme(null);
@@ -133,12 +128,6 @@ export function ThemeInstaller({
: 'light'
: options.baseTheme,
};
- if (options.overrideCss) {
- newTheme.overrideCss = validateThemeCss(options.overrideCss);
- }
- if (options.catalogTheme) {
- setCachedCatalogCss(validatedCss);
- }
onInstall(newTheme);
// Only set selectedCatalogTheme on success if it's a catalog theme
if (options.catalogTheme) {
@@ -174,10 +163,9 @@ export function ThemeInstaller({
id: generateThemeId(normalizedRepo),
errorMessage: t('Failed to load theme'),
catalogTheme: theme,
- overrideCss: pastedCss.trim() || undefined,
});
},
- [installTheme, pastedCss, t],
+ [installTheme, t],
);
const handlePastedCssChange = useCallback((value: string) => {
@@ -186,38 +174,19 @@ export function ThemeInstaller({
setError(null);
}, []);
- const handleInstallPastedCss = useCallback(() => {
- // Determine the base catalog CSS: prefer the in-session selection,
- // fall back to the previously installed catalog theme
- const hasCatalog = selectedCatalogTheme || installedTheme?.repo;
- const baseCss = selectedCatalogTheme
- ? cachedCatalogCss
- : (installedTheme?.cssContent ?? '');
- const repo = selectedCatalogTheme
- ? normalizeGitHubRepo(selectedCatalogTheme.repo)
- : (installedTheme?.repo ?? '');
-
- void installTheme({
- css: hasCatalog ? baseCss : '',
- name:
- selectedCatalogTheme?.name ?? installedTheme?.name ?? t('Custom Theme'),
- repo,
- id: repo
- ? generateThemeId(repo)
- : generateThemeId(`pasted-${Date.now()}`),
- errorMessage: t('Failed to validate theme CSS'),
- catalogTheme: selectedCatalogTheme,
- baseTheme: installedTheme?.baseTheme,
- overrideCss: pastedCss.trim() || undefined,
- });
- }, [
- pastedCss,
- selectedCatalogTheme,
- cachedCatalogCss,
- installedTheme,
- installTheme,
- t,
- ]);
+ const handleApplyOverride = useCallback(() => {
+ setError(null);
+ setErroringTheme(null);
+ try {
+ const validated = pastedCss.trim() ? validateThemeCss(pastedCss) : '';
+ setCustomCssOverride(validated);
+ setPastedCss(validated);
+ } catch (err) {
+ setError(
+ err instanceof Error ? err.message : t('Failed to validate theme CSS'),
+ );
+ }
+ }, [pastedCss, setCustomCssOverride, t]);
return (
<View
@@ -469,11 +438,7 @@ export function ThemeInstaller({
marginTop: 8,
}}
>
- <Button
- variant="normal"
- onPress={handleInstallPastedCss}
- isDisabled={isLoading}
- >
+ <Button variant="normal" onPress={handleApplyOverride}>
<Trans>Apply</Trans>
</Button>
</View>
diff --git a/packages/desktop-client/src/components/settings/Themes.test.tsx b/packages/desktop-client/src/components/settings/Themes.test.tsx
new file mode 100644
index 0000000000..0b78a25f5d
--- /dev/null
+++ b/packages/desktop-client/src/components/settings/Themes.test.tsx
@@ -0,0 +1,142 @@
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as StyleModule from '#style';
+
+import { ThemeSettings } from './Themes';
+
+const mockSwitchTheme = vi.fn();
+const mockSwitchDarkTheme = vi.fn();
+const mockSetLight = vi.fn();
+const mockSetDark = vi.fn();
+const mockSetOverride = vi.fn();
+
+let mockTheme: string = 'light';
+let mockInstalledLight: string | undefined = undefined;
+let mockInstalledDark: string | undefined = undefined;
+let mockCustomCssOverride: string | undefined = undefined;
+let mockCustomThemesEnabled = true;
+
+vi.mock('#hooks/useFeatureFlag', () => ({
+ useFeatureFlag: (flag: string) => {
+ if (flag === 'customThemes') return mockCustomThemesEnabled;
+ return false;
+ },
+}));
+
+vi.mock('#hooks/useGlobalPref', () => ({
+ useGlobalPref: (key: string) => {
+ switch (key) {
+ case 'installedCustomLightTheme':
+ return [mockInstalledLight, mockSetLight];
+ case 'installedCustomDarkTheme':
+ return [mockInstalledDark, mockSetDark];
+ case 'customCssOverride':
+ return [mockCustomCssOverride, mockSetOverride];
+ default:
+ return [undefined, vi.fn()];
+ }
+ },
+}));
+
+vi.mock('#style', async () => {
+ const actual = await vi.importActual<typeof StyleModule>('#style');
+ return {
+ ...actual,
+ useTheme: () => [mockTheme, mockSwitchTheme],
+ usePreferredDarkTheme: () => ['dark', mockSwitchDarkTheme],
+ };
+});
+
+vi.mock('#components/sidebar/SidebarProvider', () => ({
+ useSidebar: () => ({ floating: false }),
+}));
+
+vi.mock('#hooks/useThemeCatalog', () => ({
+ useThemeCatalog: () => ({ data: [], isLoading: false, error: null }),
+}));
+
+describe('ThemeSettings', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockTheme = 'light';
+ mockInstalledLight = undefined;
+ mockInstalledDark = undefined;
+ mockCustomCssOverride = undefined;
+ mockCustomThemesEnabled = true;
+ });
+
+ describe('custom CSS override indicator', () => {
+ it('is hidden when customCssOverride is undefined', () => {
+ render(<ThemeSettings />);
+ expect(
+ screen.queryByLabelText('Custom CSS override active — click to edit'),
+ ).toBeNull();
+ });
+
+ it('is hidden when customCssOverride is an empty string', () => {
+ mockCustomCssOverride = '';
+ render(<ThemeSettings />);
+ expect(
+ screen.queryByLabelText('Custom CSS override active — click to edit'),
+ ).toBeNull();
+ });
+
+ it('is hidden when customCssOverride is only whitespace', () => {
+ mockCustomCssOverride = ' \n ';
+ render(<ThemeSettings />);
+ expect(
+ screen.queryByLabelText('Custom CSS override active — click to edit'),
+ ).toBeNull();
+ });
+
+ it('is visible when customCssOverride has non-whitespace content', () => {
+ mockCustomCssOverride = ':root { --color-accent: #ff00aa; }';
+ render(<ThemeSettings />);
+ expect(
+ screen.getByLabelText('Custom CSS override active — click to edit'),
+ ).toBeVisible();
+ });
+
+ it('is hidden when customThemes feature flag is off', () => {
+ mockCustomThemesEnabled = false;
+ mockCustomCssOverride = ':root { --color-accent: #ff00aa; }';
+ render(<ThemeSettings />);
+ expect(
+ screen.queryByLabelText('Custom CSS override active — click to edit'),
+ ).toBeNull();
+ });
+
+ it('opens the installer when clicked', async () => {
+ const user = userEvent.setup();
+ mockCustomCssOverride = ':root { --color-accent: #ff00aa; }';
+ render(<ThemeSettings />);
+ await user.click(
+ screen.getByLabelText('Custom CSS override active — click to edit'),
+ );
+ // Installer heading appears on open
+ expect(screen.getByText('Install Custom Theme')).toBeVisible();
+ });
+ });
+
+ describe('built-in theme selection preserves override', () => {
+ it('does not call setCustomCssOverride when switching to a built-in theme', async () => {
+ const user = userEvent.setup();
+ mockCustomCssOverride = ':root { --color-accent: #ff00aa; }';
+ render(<ThemeSettings />);
+
+ // The Select trigger is the only "Light" button before the dropdown
+ // is opened. Click it to reveal the menu.
+ const select = screen.getByRole('button', { name: 'Light' });
+ await user.click(select);
+ // The Select component renders menu items as buttons (not options).
+ // After opening, "Dark" appears as a button in the popover.
+ const darkOption = await screen.findByRole('button', { name: 'Dark' });
+ await user.click(darkOption);
+
+ expect(mockSetOverride).not.toHaveBeenCalled();
+ expect(mockSwitchTheme).toHaveBeenCalledWith('dark');
+ });
+ });
+});
diff --git a/packages/desktop-client/src/components/settings/Themes.tsx b/packages/desktop-client/src/components/settings/Themes.tsx
index e25f2c9dbc..ab021c0498 100644
--- a/packages/desktop-client/src/components/settings/Themes.tsx
+++ b/packages/desktop-client/src/components/settings/Themes.tsx
@@ -1,6 +1,8 @@
-import React, { useCallback, useState } from 'react';
+import React, { useCallback, useRef, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
+import { Button } from '@actual-app/components/button';
+import { SvgCode } from '@actual-app/components/icons/v1';
import { Menu } from '@actual-app/components/menu';
import { Select } from '@actual-app/components/select';
import { Text } from '@actual-app/components/text';
@@ -32,14 +34,20 @@ const INSTALL_NEW_VALUE = '__install_new__';
const INSTALL_CUSTOM_LIGHT = '__install_custom_light__';
const INSTALL_CUSTOM_DARK = '__install_custom_dark__';
+type InstallerState = {
+ slot: 'light' | 'dark';
+ catalogMode?: 'light' | 'dark';
+ switchThemeOnSuccess?: Theme;
+} | null;
+
export function ThemeSettings() {
const { t } = useTranslation();
const sidebar = useSidebar();
const [theme, switchTheme] = useTheme();
const [darkTheme, switchDarkTheme] = usePreferredDarkTheme();
- const [showInstaller, setShowInstaller] = useState<
- 'single' | 'light' | 'dark' | null
- >(null);
+ const [showInstaller, setShowInstaller] = useState<InstallerState>(null);
+ const showInstallerRef = useRef<InstallerState>(null);
+ showInstallerRef.current = showInstaller;
const customThemesEnabled = useFeatureFlag('customThemes');
@@ -50,6 +58,8 @@ export function ThemeSettings() {
const [installedDarkThemeJson, setInstalledDarkThemeJson] = useGlobalPref(
'installedCustomDarkTheme',
);
+ const [customCssOverride] = useGlobalPref('customCssOverride');
+ const hasCustomCssOverride = Boolean(customCssOverride?.trim());
const installedCustomLightTheme = parseInstalledTheme(
installedLightThemeJson,
@@ -124,7 +134,10 @@ export function ThemeSettings() {
const handleThemeChange = useCallback(
(value: string) => {
if (value === INSTALL_NEW_VALUE) {
- setShowInstaller('single');
+ setShowInstaller({
+ slot: 'light',
+ switchThemeOnSuccess: theme === 'auto' ? 'light' : undefined,
+ });
return;
}
@@ -134,14 +147,14 @@ export function ThemeSettings() {
switchTheme(value as Theme);
}
},
- [setInstalledLightThemeJson, setInstalledDarkThemeJson, switchTheme],
+ [theme, setInstalledLightThemeJson, setInstalledDarkThemeJson, switchTheme],
);
// Handle light theme selection (auto mode)
const handleLightThemeChange = useCallback(
(value: string) => {
if (value === INSTALL_CUSTOM_LIGHT) {
- setShowInstaller('light');
+ setShowInstaller({ slot: 'light', catalogMode: 'light' });
return;
}
if (value === 'light') {
@@ -155,7 +168,7 @@ export function ThemeSettings() {
const handleDarkThemeChange = useCallback(
(value: string) => {
if (value === INSTALL_CUSTOM_DARK) {
- setShowInstaller('dark');
+ setShowInstaller({ slot: 'dark', catalogMode: 'dark' });
return;
}
if (!value.startsWith('custom-dark:')) {
@@ -166,27 +179,22 @@ export function ThemeSettings() {
[setInstalledDarkThemeJson, switchDarkTheme],
);
- // Handle theme installation
const handleInstall = useCallback(
(newTheme: InstalledTheme) => {
- if (showInstaller === 'light') {
- setInstalledLightThemeJson(serializeInstalledTheme(newTheme));
- } else if (showInstaller === 'dark') {
+ // Read via ref so a late-resolving install (dialog already closed) is
+ // dropped instead of writing to a stale slot.
+ const current = showInstallerRef.current;
+ if (!current) return;
+ if (current.slot === 'dark') {
setInstalledDarkThemeJson(serializeInstalledTheme(newTheme));
} else {
setInstalledLightThemeJson(serializeInstalledTheme(newTheme));
- if (theme === 'auto') {
- switchTheme('light');
- }
+ }
+ if (current.switchThemeOnSuccess) {
+ switchTheme(current.switchThemeOnSuccess);
}
},
- [
- showInstaller,
- theme,
- setInstalledLightThemeJson,
- setInstalledDarkThemeJson,
- switchTheme,
- ],
+ [setInstalledLightThemeJson, setInstalledDarkThemeJson, switchTheme],
);
// Handle installer close
@@ -194,6 +202,14 @@ export function ThemeSettings() {
setShowInstaller(null);
}, []);
+ const handleEditOverride = useCallback(() => {
+ setShowInstaller(
+ theme === 'auto'
+ ? { slot: 'light', catalogMode: 'light' }
+ : { slot: 'light' },
+ );
+ }, [theme]);
+
return (
<Setting
primaryAction={
@@ -220,17 +236,41 @@ export function ThemeSettings() {
}}
>
<Column title={t('Theme')}>
- <Select<string>
- onChange={handleThemeChange}
- value={getCurrentValue()}
- options={buildOptions()}
- className={css({
- '&[data-hovered]': {
- backgroundColor: themeStyle.buttonNormalBackgroundHover,
- },
- maxWidth: '100%',
- })}
- />
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 8,
+ }}
+ >
+ <Select<string>
+ onChange={handleThemeChange}
+ value={getCurrentValue()}
+ options={buildOptions()}
+ className={css({
+ '&[data-hovered]': {
+ backgroundColor: themeStyle.buttonNormalBackgroundHover,
+ },
+ maxWidth: '100%',
+ })}
+ />
+ {customThemesEnabled && hasCustomCssOverride && (
+ <Button
+ variant="bare"
+ aria-label={t(
+ 'Custom CSS override active — click to edit',
+ )}
+ onPress={handleEditOverride}
+ style={{
+ color: themeStyle.pageTextPositive,
+ gap: 6,
+ }}
+ >
+ <Trans>Custom CSS is active</Trans>
+ <SvgCode style={{ width: 14, height: 14 }} />
+ </Button>
+ )}
+ </View>
</Column>
{theme === 'auto' && (
<>
@@ -280,15 +320,11 @@ export function ThemeSettings() {
onInstall={handleInstall}
onClose={handleInstallerClose}
installedTheme={
- showInstaller === 'dark'
+ showInstaller.slot === 'dark'
? installedCustomDarkTheme
: installedCustomLightTheme
}
- mode={
- showInstaller === 'light' || showInstaller === 'dark'
- ? showInstaller
- : undefined
- }
+ mode={showInstaller.catalogMode}
/>
)}
</View>
diff --git a/packages/desktop-client/src/style/customThemes.test.ts b/packages/desktop-client/src/style/customThemes.test.ts
index 71c8b4041c..aabf042632 100644
--- a/packages/desktop-client/src/style/customThemes.test.ts
+++ b/packages/desktop-client/src/style/customThemes.test.ts
@@ -3,7 +3,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
embedThemeFonts,
+ extractLegacyOverride,
MAX_FONT_FILE_SIZE,
+ migrateLegacyOverride,
parseInstalledTheme,
validateThemeCss,
} from './customThemes';
@@ -1245,6 +1247,26 @@ describe('parseInstalledTheme', () => {
expect(result?.cssContent).toBe(':root { --color-primary: #007bff; }');
});
+ it('ignores legacy overrideCss field without rejecting the theme', () => {
+ const theme = {
+ id: 'theme-legacy',
+ name: 'Legacy Theme',
+ repo: 'owner/repo',
+ cssContent: ':root { --color-primary: #007bff; }',
+ overrideCss: ':root { --color-accent: #ff00aa; }',
+ };
+ const json = JSON.stringify(theme);
+
+ const result = parseInstalledTheme(json);
+
+ expect(result).not.toBeNull();
+ expect(result?.id).toBe('theme-legacy');
+ expect(result?.cssContent).toBe(':root { --color-primary: #007bff; }');
+ // Legacy field is stripped from the typed result. extractLegacyOverride
+ // is the helper that reads it off the raw JSON during migration.
+ expect(result).not.toHaveProperty('overrideCss');
+ });
+
it('should parse theme with empty string fields', () => {
const theme: InstalledTheme = {
id: '',
@@ -1592,3 +1614,239 @@ describe('embedThemeFonts', () => {
expect(result).toBe(css);
});
});
+
+describe('extractLegacyOverride', () => {
+ it('returns the overrideCss string when present and non-empty', () => {
+ const json = JSON.stringify({
+ id: 'theme-abc',
+ name: 'My Theme',
+ repo: 'owner/repo',
+ cssContent: ':root { --color-primary: #007bff; }',
+ overrideCss: ':root { --color-accent: #ff00aa; }',
+ });
+ expect(extractLegacyOverride(json)).toBe(
+ ':root { --color-accent: #ff00aa; }',
+ );
+ });
+
+ it('returns null when overrideCss is missing', () => {
+ const json = JSON.stringify({
+ id: 'theme-abc',
+ name: 'My Theme',
+ repo: 'owner/repo',
+ cssContent: ':root { --color-primary: #007bff; }',
+ });
+ expect(extractLegacyOverride(json)).toBeNull();
+ });
+
+ it('returns null when overrideCss is an empty string', () => {
+ const json = JSON.stringify({
+ id: 'theme-abc',
+ name: 'My Theme',
+ repo: 'owner/repo',
+ cssContent: ':root { --color-primary: #007bff; }',
+ overrideCss: '',
+ });
+ expect(extractLegacyOverride(json)).toBeNull();
+ });
+
+ it('returns null when overrideCss is only whitespace', () => {
+ const json = JSON.stringify({
+ id: 'theme-abc',
+ name: 'My Theme',
+ repo: 'owner/repo',
+ cssContent: ':root { --color-primary: #007bff; }',
+ overrideCss: ' \n\t ',
+ });
+ expect(extractLegacyOverride(json)).toBeNull();
+ });
+
+ it('trims leading and trailing whitespace from overrideCss', () => {
+ const json = JSON.stringify({
+ id: 'theme-abc',
+ name: 'My Theme',
+ repo: 'owner/repo',
+ cssContent: ':root { --color-primary: #007bff; }',
+ overrideCss: ' :root { --color-accent: #ff00aa; } ',
+ });
+ expect(extractLegacyOverride(json)).toBe(
+ ':root { --color-accent: #ff00aa; }',
+ );
+ });
+
+ it('returns null when overrideCss is not a string', () => {
+ const json = JSON.stringify({
+ id: 'theme-abc',
+ name: 'My Theme',
+ repo: 'owner/repo',
+ cssContent: ':root { --color-primary: #007bff; }',
+ overrideCss: 42,
+ });
+ expect(extractLegacyOverride(json)).toBeNull();
+ });
+
+ it('returns null for undefined input', () => {
+ expect(extractLegacyOverride(undefined)).toBeNull();
+ });
+
+ it('returns null for empty string input', () => {
+ expect(extractLegacyOverride('')).toBeNull();
+ });
+
+ it('returns null for malformed JSON', () => {
+ expect(extractLegacyOverride('{ not valid json')).toBeNull();
+ });
+
+ it('returns null when parsed value is not an object', () => {
+ expect(extractLegacyOverride(JSON.stringify('a string'))).toBeNull();
+ expect(extractLegacyOverride(JSON.stringify(null))).toBeNull();
+ expect(extractLegacyOverride(JSON.stringify([]))).toBeNull();
+ });
+});
+
+describe('migrateLegacyOverride', () => {
+ const baseTheme = {
+ id: 'theme-abc',
+ name: 'My Theme',
+ repo: 'owner/repo',
+ cssContent: ':root { --color-primary: #007bff; }',
+ };
+
+ it('returns null when existingOverride already has content', () => {
+ const lightJson = JSON.stringify({
+ ...baseTheme,
+ overrideCss: ':root { --color-accent: red; }',
+ });
+ expect(
+ migrateLegacyOverride({
+ existingOverride: ':root { --color-accent: blue; }',
+ lightJson,
+ darkJson: undefined,
+ }),
+ ).toBeNull();
+ });
+
+ it('returns null when neither installed theme has legacy overrideCss', () => {
+ const lightJson = JSON.stringify(baseTheme);
+ const darkJson = JSON.stringify(baseTheme);
+ expect(
+ migrateLegacyOverride({
+ existingOverride: undefined,
+ lightJson,
+ darkJson,
+ }),
+ ).toBeNull();
+ });
+
+ it('migrates from light when only light has legacy overrideCss', () => {
+ const lightJson = JSON.stringify({
+ ...baseTheme,
+ overrideCss: ':root { --color-accent: #ff00aa; }',
+ });
+ const darkJson = JSON.stringify(baseTheme);
+ const result = migrateLegacyOverride({
+ existingOverride: undefined,
+ lightJson,
+ darkJson,
+ });
+ expect(result).not.toBeNull();
+ expect(result?.override).toBe(':root { --color-accent: #ff00aa; }');
+ expect(result?.newLightJson).toBe(JSON.stringify(baseTheme));
+ expect(result?.newDarkJson).toBe(darkJson);
+ expect(
+ JSON.parse(result?.newLightJson ?? '{}').overrideCss,
+ ).toBeUndefined();
+ });
+
+ it('migrates from dark when only dark has legacy overrideCss', () => {
+ const lightJson = JSON.stringify(baseTheme);
+ const darkJson = JSON.stringify({
+ ...baseTheme,
+ overrideCss: ':root { --color-accent: #00ffaa; }',
+ });
+ const result = migrateLegacyOverride({
+ existingOverride: undefined,
+ lightJson,
+ darkJson,
+ });
+ expect(result).not.toBeNull();
+ expect(result?.override).toBe(':root { --color-accent: #00ffaa; }');
+ expect(result?.newLightJson).toBe(lightJson);
+ expect(result?.newDarkJson).toBe(JSON.stringify(baseTheme));
+ expect(JSON.parse(result?.newDarkJson ?? '{}').overrideCss).toBeUndefined();
+ });
+
+ it('prefers light when both have legacy overrideCss (collision rule)', () => {
+ const lightJson = JSON.stringify({
+ ...baseTheme,
+ overrideCss: ':root { --color-accent: red; }',
+ });
+ const darkJson = JSON.stringify({
+ ...baseTheme,
+ overrideCss: ':root { --color-accent: blue; }',
+ });
+ const result = migrateLegacyOverride({
+ existingOverride: undefined,
+ lightJson,
+ darkJson,
+ });
+ expect(result?.override).toBe(':root { --color-accent: red; }');
+ expect(result?.newLightJson).toBe(JSON.stringify(baseTheme));
+ expect(result?.newDarkJson).toBe(JSON.stringify(baseTheme));
+ expect(
+ JSON.parse(result?.newLightJson ?? '{}').overrideCss,
+ ).toBeUndefined();
+ expect(JSON.parse(result?.newDarkJson ?? '{}').overrideCss).toBeUndefined();
+ });
+
+ it('migrates from light when existingOverride is an empty string', () => {
+ const lightJson = JSON.stringify({
+ ...baseTheme,
+ overrideCss: ':root { --color-accent: red; }',
+ });
+ const result = migrateLegacyOverride({
+ existingOverride: '',
+ lightJson,
+ darkJson: undefined,
+ });
+ expect(result?.override).toBe(':root { --color-accent: red; }');
+ });
+
+ it('migrates when existingOverride is only whitespace', () => {
+ const lightJson = JSON.stringify({
+ ...baseTheme,
+ overrideCss: ':root { --color-accent: red; }',
+ });
+ const result = migrateLegacyOverride({
+ existingOverride: ' \n ',
+ lightJson,
+ darkJson: undefined,
+ });
+ expect(result?.override).toBe(':root { --color-accent: red; }');
+ });
+
+ it('handles undefined installed theme JSONs', () => {
+ const result = migrateLegacyOverride({
+ existingOverride: undefined,
+ lightJson: undefined,
+ darkJson: undefined,
+ });
+ expect(result).toBeNull();
+ });
+
+ it('returns the untouched side by reference when only one side migrates', () => {
+ const lightJson = JSON.stringify({
+ ...baseTheme,
+ overrideCss: ':root { --color-accent: red; }',
+ });
+ const darkJson = JSON.stringify(baseTheme);
+ const result = migrateLegacyOverride({
+ existingOverride: undefined,
+ lightJson,
+ darkJson,
+ });
+ // The dark side had no legacy override, so it is returned unchanged
+ // (same reference, not a re-serialized copy).
+ expect(result?.newDarkJson).toBe(darkJson);
+ });
+});
diff --git a/packages/desktop-client/src/style/customThemes.ts b/packages/desktop-client/src/style/customThemes.ts
index 417ed35dc7..6a1242bc09 100644
--- a/packages/desktop-client/src/style/customThemes.ts
+++ b/packages/desktop-client/src/style/customThemes.ts
@@ -18,7 +18,6 @@ export type InstalledTheme = {
repo: string;
cssContent: string; // CSS content stored when theme is installed (required)
baseTheme?: BaseTheme; // Which built-in theme to use as base (defaults to contextual theme)
- overrideCss?: string; // Additional free-text CSS overrides on top of cssContent
};
/**
@@ -624,21 +623,6 @@ export async function embedThemeFonts(
return result;
}
-/**
- * Validate and concatenate cssContent and overrideCss into a single CSS string.
- * Returns empty string if neither is present.
- */
-export function validateAndCombineThemeCss(
- cssContent?: string,
- overrideCss?: string,
-): string {
- const parts = [
- cssContent && validateThemeCss(cssContent),
- overrideCss && validateThemeCss(overrideCss),
- ].filter(Boolean);
- return parts.join('\n');
-}
-
/**
* Generate a unique ID for a theme based on its repo URL or direct CSS URL.
*/
@@ -685,9 +669,6 @@ export function parseInstalledTheme(
) {
result.baseTheme = parsed.baseTheme as BaseTheme;
}
- if (typeof parsed.overrideCss === 'string' && parsed.overrideCss) {
- result.overrideCss = parsed.overrideCss;
- }
return result;
}
return null;
@@ -702,3 +683,82 @@ export function parseInstalledTheme(
export function serializeInstalledTheme(theme: InstalledTheme | null): string {
return JSON.stringify(theme);
}
+
+/**
+ * Extract the legacy `overrideCss` field from an installed theme JSON string.
+ * Used by the one-time migration that moves the field out of InstalledTheme
+ * and into the standalone `customCssOverride` global pref.
+ *
+ * Returns null if the JSON is missing, malformed, not an object, or does not
+ * contain a non-whitespace string `overrideCss` field. Leading/trailing
+ * whitespace is stripped from the returned value.
+ */
+export function extractLegacyOverride(json: string | undefined): string | null {
+ if (!json) return null;
+ try {
+ const parsed = JSON.parse(json);
+ if (
+ parsed &&
+ typeof parsed === 'object' &&
+ !Array.isArray(parsed) &&
+ typeof parsed.overrideCss === 'string'
+ ) {
+ const trimmed = parsed.overrideCss.trim();
+ if (trimmed.length > 0) {
+ return trimmed;
+ }
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * One-time migration helper: moves a legacy `overrideCss` field out of the
+ * installed theme JSON blobs and into the standalone customCssOverride value.
+ *
+ * Collision rule: if both light and dark carry a legacy override, light wins.
+ * The other is silently dropped — users wrote one shared override in the UI
+ * today; two different values is a pathological case that only shows up if
+ * someone edited prefs.json by hand.
+ *
+ * Returns null when no migration is needed. Otherwise returns the migrated
+ * override plus the re-serialized installed theme JSONs (with `overrideCss`
+ * stripped). Callers write all three values back to global prefs.
+ */
+export function migrateLegacyOverride(params: {
+ existingOverride: string | undefined;
+ lightJson: string | undefined;
+ darkJson: string | undefined;
+}): {
+ override: string;
+ newLightJson: string | undefined;
+ newDarkJson: string | undefined;
+} | null {
+ const { existingOverride, lightJson, darkJson } = params;
+
+ if (existingOverride?.trim()) {
+ return null;
+ }
+
+ const lightLegacy = extractLegacyOverride(lightJson);
+ const darkLegacy = extractLegacyOverride(darkJson);
+ const legacy = lightLegacy ?? darkLegacy;
+ if (!legacy) {
+ return null;
+ }
+
+ // parseInstalledTheme strips any unknown fields (including the legacy
+ // overrideCss) by building the result from explicit field assignments.
+ const stripOverride = (json: string | undefined): string | undefined => {
+ const parsed = parseInstalledTheme(json);
+ return parsed ? serializeInstalledTheme(parsed) : json;
+ };
+
+ return {
+ override: legacy,
+ newLightJson: lightLegacy ? stripOverride(lightJson) : lightJson,
+ newDarkJson: darkLegacy ? stripOverride(darkJson) : darkJson,
+ };
+}
diff --git a/packages/desktop-client/src/style/theme.tsx b/packages/desktop-client/src/style/theme.tsx
index 800a188fde..e924e297f5 100644
--- a/packages/desktop-client/src/style/theme.tsx
+++ b/packages/desktop-client/src/style/theme.tsx
@@ -6,8 +6,9 @@ import { useFeatureFlag } from '#hooks/useFeatureFlag';
import { useGlobalPref } from '#hooks/useGlobalPref';
import {
+ migrateLegacyOverride,
parseInstalledTheme,
- validateAndCombineThemeCss,
+ validateThemeCss,
} from './customThemes';
import type { BaseTheme } from './customThemes';
import * as darkTheme from './themes/dark';
@@ -43,6 +44,56 @@ export function usePreferredDarkTheme() {
return [darkTheme, setDarkTheme] as const;
}
+/**
+ * One-time migration: moves any legacy `overrideCss` field out of the
+ * installed theme JSON blobs and into the new `customCssOverride` global pref.
+ * Gated on the customThemes feature flag — users who never used the feature
+ * have nothing to migrate.
+ *
+ * TODO: remove this after v26.6.0 is released
+ */
+function useMigrateLegacyOverride() {
+ const customThemesEnabled = useFeatureFlag('customThemes');
+ const [customCssOverride, setCustomCssOverride] =
+ useGlobalPref('customCssOverride');
+ const [installedCustomLightThemeJson, setInstalledCustomLightThemeJson] =
+ useGlobalPref('installedCustomLightTheme');
+ const [installedCustomDarkThemeJson, setInstalledCustomDarkThemeJson] =
+ useGlobalPref('installedCustomDarkTheme');
+
+ useEffect(() => {
+ if (!customThemesEnabled) return;
+
+ const result = migrateLegacyOverride({
+ existingOverride: customCssOverride,
+ lightJson: installedCustomLightThemeJson,
+ darkJson: installedCustomDarkThemeJson,
+ });
+
+ if (!result) return;
+
+ setCustomCssOverride(result.override);
+ if (result.newLightJson !== installedCustomLightThemeJson) {
+ setInstalledCustomLightThemeJson(result.newLightJson);
+ }
+ if (result.newDarkJson !== installedCustomDarkThemeJson) {
+ setInstalledCustomDarkThemeJson(result.newDarkJson);
+ }
+ // Re-runs when prefs hydrate so migration isn't missed if the installed
+ // theme JSONs arrive after the first render. migrateLegacyOverride is
+ // idempotent: once customCssOverride is set (or the legacy field is
+ // stripped), subsequent invocations return null.
+ }, [
+ customThemesEnabled,
+ customCssOverride,
+ installedCustomLightThemeJson,
+ installedCustomDarkThemeJson,
+ setCustomCssOverride,
+ setInstalledCustomLightThemeJson,
+ setInstalledCustomDarkThemeJson,
+ ]);
+}
+
function getBaseThemeColors(baseTheme: BaseTheme) {
return themes[baseTheme]?.colors;
}
@@ -144,6 +195,7 @@ export function ThemeStyle() {
* injected via @media (prefers-color-scheme) rules. Otherwise, a single custom theme applies.
*/
export function CustomThemeStyle() {
+ useMigrateLegacyOverride();
const customThemesEnabled = useFeatureFlag('customThemes');
const [activeTheme] = useTheme();
const [installedCustomLightThemeJson] = useGlobalPref(
@@ -152,61 +204,57 @@ export function CustomThemeStyle() {
const [installedCustomDarkThemeJson] = useGlobalPref(
'installedCustomDarkTheme',
);
+ const [customCssOverride] = useGlobalPref('customCssOverride');
const validatedCss = useMemo(() => {
if (!customThemesEnabled) return null;
- if (activeTheme === 'auto') {
- const lightTheme = parseInstalledTheme(installedCustomLightThemeJson);
- const darkTheme = parseInstalledTheme(installedCustomDarkThemeJson);
-
- let css = '';
-
+ const safeValidate = (css: string | undefined, errorLabel: string) => {
+ if (!css?.trim()) return '';
try {
- const lightCss = validateAndCombineThemeCss(
- lightTheme?.cssContent,
- lightTheme?.overrideCss,
- );
- if (lightCss) {
- css += `@media (prefers-color-scheme: light) { ${lightCss} }\n`;
- }
+ return validateThemeCss(css);
} catch (error) {
- console.error('Invalid custom light theme CSS', { error });
+ console.error(errorLabel, { error });
+ return '';
}
+ };
- try {
- const darkCss = validateAndCombineThemeCss(
- darkTheme?.cssContent,
- darkTheme?.overrideCss,
- );
- if (darkCss) {
- css += `@media (prefers-color-scheme: dark) { ${darkCss} }\n`;
- }
- } catch (error) {
- console.error('Invalid custom dark theme CSS', { error });
+ let baseCss = '';
+ if (activeTheme === 'auto') {
+ const lightCss = safeValidate(
+ parseInstalledTheme(installedCustomLightThemeJson)?.cssContent,
+ 'Invalid custom light theme CSS',
+ );
+ if (lightCss) {
+ baseCss += `@media (prefers-color-scheme: light) { ${lightCss} }\n`;
}
-
- return css || null;
+ const darkCss = safeValidate(
+ parseInstalledTheme(installedCustomDarkThemeJson)?.cssContent,
+ 'Invalid custom dark theme CSS',
+ );
+ if (darkCss) {
+ baseCss += `@media (prefers-color-scheme: dark) { ${darkCss} }\n`;
+ }
+ } else {
+ baseCss = safeValidate(
+ parseInstalledTheme(installedCustomLightThemeJson)?.cssContent,
+ 'Invalid custom theme CSS',
+ );
}
- const installedTheme = parseInstalledTheme(installedCustomLightThemeJson);
+ const overrideLayer = safeValidate(
+ customCssOverride,
+ 'Invalid custom CSS override',
+ );
- try {
- return (
- validateAndCombineThemeCss(
- installedTheme?.cssContent,
- installedTheme?.overrideCss,
- ) || null
- );
- } catch (error) {
- console.error('Invalid custom theme CSS', { error });
- return null;
- }
+ const combined = [baseCss, overrideLayer].filter(Boolean).join('\n');
+ return combined || null;
}, [
customThemesEnabled,
activeTheme,
installedCustomLightThemeJson,
installedCustomDarkThemeJson,
+ customCssOverride,
]);
if (!validatedCss) {
diff --git a/packages/loot-core/src/server/preferences/app.ts b/packages/loot-core/src/server/preferences/app.ts
index 3d9e295593..81818149a0 100644
--- a/packages/loot-core/src/server/preferences/app.ts
+++ b/packages/loot-core/src/server/preferences/app.ts
@@ -107,6 +107,9 @@ async function saveGlobalPrefs(prefs: GlobalPrefs) {
prefs.installedCustomDarkTheme,
);
}
+ if (prefs.customCssOverride !== undefined) {
+ await asyncStorage.setItem('custom-css-override', prefs.customCssOverride);
+ }
if (prefs.serverSelfSignedCert !== undefined) {
await asyncStorage.setItem(
'server-self-signed-cert',
@@ -137,6 +140,7 @@ async function loadGlobalPrefs(): Promise<GlobalPrefs> {
'preferred-dark-theme': preferredDarkTheme,
'installed-custom-theme': installedCustomLightTheme,
'installed-custom-dark-theme': installedCustomDarkTheme,
+ 'custom-css-override': customCssOverride,
'server-self-signed-cert': serverSelfSignedCert,
syncServerConfig,
notifyWhenUpdateIsAvailable,
@@ -151,6 +155,7 @@ async function loadGlobalPrefs(): Promise<GlobalPrefs> {
'preferred-dark-theme',
'installed-custom-theme',
'installed-custom-dark-theme',
+ 'custom-css-override',
'server-self-signed-cert',
'syncServerConfig',
'notifyWhenUpdateIsAvailable',
@@ -175,6 +180,7 @@ async function loadGlobalPrefs(): Promise<GlobalPrefs> {
: 'dark',
installedCustomLightTheme: installedCustomLightTheme || undefined,
installedCustomDarkTheme: installedCustomDarkTheme || undefined,
+ customCssOverride: customCssOverride || undefined,
serverSelfSignedCert: serverSelfSignedCert || undefined,
syncServerConfig: syncServerConfig || undefined,
notifyWhenUpdateIsAvailable:
diff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.ts
index 8ac7256d52..de57a7e27a 100644
--- a/packages/loot-core/src/types/prefs.ts
+++ b/packages/loot-core/src/types/prefs.ts
@@ -119,6 +119,7 @@ export type GlobalPrefs = Partial<{
>; // Complete plugin theme metadata
installedCustomLightTheme?: string; // JSON of InstalledTheme for light custom theme (also used as single custom theme in non-auto mode)
installedCustomDarkTheme?: string; // JSON of InstalledTheme for auto-mode dark custom theme
+ customCssOverride?: string; // User-pasted CSS override applied on top of any theme. Empty string or undefined means no override.
documentDir: string; // Electron only
serverSelfSignedCert: string; // Electron only
syncServerConfig?: {
@@ -149,6 +150,7 @@ export type GlobalPrefsJson = Partial<{
'preferred-dark-theme'?: GlobalPrefs['preferredDarkTheme'];
'installed-custom-theme'?: GlobalPrefs['installedCustomLightTheme'];
'installed-custom-dark-theme'?: GlobalPrefs['installedCustomDarkTheme'];
+ 'custom-css-override'?: GlobalPrefs['customCssOverride'];
plugins?: string; // "true" or "false"
'plugin-theme'?: string; // JSON string of complete plugin theme (current selected plugin theme)
'server-self-signed-cert'?: GlobalPrefs['serverSelfSignedCert'];
diff --git a/upcoming-release-notes/7495.md b/upcoming-release-notes/7495.md
new file mode 100644
index 0000000000..cd1a490b3c
--- /dev/null
+++ b/upcoming-release-notes/7495.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [MatissJanis]
+---
+
+Custom Themes: custom CSS overrides now persist across theme changes and show a visible indicator next to the Theme dropdown when active