Open-source personal finance manager. Self-hosted, privacy-first.
feat: add custom colors for theme (#254)
Alex Torresc828250ed871
diff --git a/backend/app/api/admin.py b/backend/app/api/admin.pyindex 6e488d52..9f924eac 100644--- a/backend/app/api/admin.py+++ b/backend/app/api/admin.py@@ -1,4 +1,5 @@import uuid+import refrom fastapi import APIRouter, Depends, HTTPException, Query, Request, statusfrom sqlalchemy.ext.asyncio import AsyncSession@@ -22,6 +23,8 @@ ALLOWED_SETTINGS = {"registration_enabled","credit_card_accounting_mode","use_provider_categories",+ "theme_color_light",+ "theme_color_dark",}@@ -125,11 +128,20 @@ async def update_setting("credit_card_accounting_mode": {"cash", "accrual"},"use_provider_categories": {"true", "false"},}+if key in SETTING_VALIDATORS and data.value not in SETTING_VALIDATORS[key]:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,detail=f"Invalid value for '{key}'. Allowed: {SETTING_VALIDATORS[key]}",)++ if key in ("theme_color_light", "theme_color_dark"):+ if not re.match(r"^#[0-9A-Fa-f]{6}$", data.value):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=f"Invalid hex color code for '{key}'. Expected format: #RRGGBB",+ )+setting = await admin_service.set_app_setting(session, key, data.value)return AppSettingRead.model_validate(setting)@@ -142,6 +154,15 @@ async def registration_status(return {"enabled": enabled}[email protected]("/default-colors")+async def default_colors(+ session: AsyncSession = Depends(get_async_session),+):+ light = await admin_service.get_app_setting(session, "theme_color_light")+ dark = await admin_service.get_app_setting(session, "theme_color_dark")+ return {"light": light.value if light else None, "dark": dark.value if dark else None}++@router.get("/accounting-mode")async def accounting_mode(session: AsyncSession = Depends(get_async_session),diff --git a/backend/tests/test_admin_api.py b/backend/tests/test_admin_api.pyindex a2b25bb1..2778861e 100644--- a/backend/tests/test_admin_api.py+++ b/backend/tests/test_admin_api.py@@ -469,3 +469,51 @@ class TestUseProviderCategoriesToggle:headers=auth_headers,)assert response.status_code == 403+++class TestThemeSettings:+ """Test theme color settings and the public default-colors endpoint."""++ async def test_get_default_colors_empty(self, client: AsyncClient, clean_db):+ response = await client.get("/api/admin/default-colors")+ assert response.status_code == 200+ assert response.json() == {"light": None, "dark": None}++ async def test_get_default_colors_populated(self, client: AsyncClient, session: AsyncSession, clean_db):+ session.add_all([+ AppSetting(key="theme_color_light", value="#FFFFFF"),+ AppSetting(key="theme_color_dark", value="#000000"),+ ])+ await session.commit()++ response = await client.get("/api/admin/default-colors")+ assert response.status_code == 200+ assert response.json() == {"light": "#FFFFFF", "dark": "#000000"}++ async def test_update_theme_color_valid(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):+ response = await client.patch(+ "/api/admin/settings/theme_color_light",+ json={"value": "#6366F1"},+ headers=admin_auth_headers,+ )+ assert response.status_code == 200+ assert response.json()["value"] == "#6366F1"++ @pytest.mark.parametrize("invalid_color", [+ "6366F1", # missing #+ "#6366F", # too short+ "#6366F11", # too long+ "#GGGGGG", # invalid hex chars+ "red", # named color+ "#123", # 3-digit hex (not allowed by regex)+ ])+ async def test_update_theme_color_invalid(+ self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User, invalid_color: str+ ):+ response = await client.patch(+ "/api/admin/settings/theme_color_light",+ json={"value": invalid_color},+ headers=admin_auth_headers,+ )+ assert response.status_code == 400+ assert "invalid hex color code" in response.json()["detail"].lower()diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex 8e14af36..616b5507 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -4,7 +4,7 @@ import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useQuery } from '@tanstack/react-query'import { useAuth } from '@/contexts/auth-context'-import { auth as authApi, backup as backupApi } from '@/lib/api'+import { auth as authApi, backup as backupApi, admin as adminApi } from '@/lib/api'import { resolveSupportedLang } from '@/lib/i18n'import { toast } from 'sonner'import { OnboardingTour } from '@/components/onboarding-tour'@@ -64,6 +64,7 @@ import { useCommandPaletteHotkey } from '@/hooks/use-command-palette-hotkey'import { GlobalChatPanel } from '@/components/global-chat-panel'import { useFeatureFlags } from '@/hooks/use-feature-flags'import { Bot, Search, Sparkles } from 'lucide-react'+import { setThemeBasedOnSystem } from '@/lib/theme-utils'type NavItem =| { type: 'link'; key: string; path: string; icon: React.ElementType }@@ -102,7 +103,7 @@ export function AppLayout() {const { user, logout, updateUser } = useAuth()const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.language- const { theme, setTheme } = useTheme()+ const { theme, setTheme, resolvedTheme } = useTheme()const location = useLocation()const [sidebarOpen, setSidebarOpen] = useState(false)const [accountsExpanded, setAccountsExpanded] = useState(true)@@ -116,11 +117,16 @@ export function AppLayout() {const [updateDialogOpen, setUpdateDialogOpen] = useState(false)useCommandPaletteHotkey(setPaletteOpen)const { agentsEnabled } = useFeatureFlags()+// ⌘J / Ctrl+J toggles the global slide-over chat from anywhere.// Distinct from ⌘K (command palette) so users can have both open.// Gated on agentsEnabled so the hotkey is a no-op when the feature is// off — keeps ⌘J free for browsers/other tools.useEffect(() => {+ adminApi.defaultColors().then(({ light, dark }) => {+ setThemeBasedOnSystem(light, dark, resolvedTheme)+ }).catch(() => {})+if (!agentsEnabled) returnconst handler = (e: KeyboardEvent) => {const isMod = e.metaKey || e.ctrlKey@@ -131,7 +137,7 @@ export function AppLayout() {}document.addEventListener('keydown', handler)return () => document.removeEventListener('keydown', handler)- }, [agentsEnabled])+ }, [agentsEnabled, resolvedTheme])// The "Agents" management page used to live in the sidebar, but it's// a configuration surface (KB upload, providers, default selection),// not a daily destination. Moved to the user menu (Change password,@@ -161,9 +167,9 @@ export function AppLayout() {}, [user, updateUser])const userInitial = user?.email?.charAt(0).toUpperCase() ?? '?'- const resolvedTheme = theme === 'system' ? undefined : theme- const isDark = resolvedTheme- ? resolvedTheme === 'dark'+ const resolvedThemeLocal = theme === 'system' ? undefined : theme+ const isDark = resolvedThemeLocal+ ? resolvedThemeLocal === 'dark': typeof window !== 'undefined' &&window.matchMedia?.('(prefers-color-scheme: dark)').matchesconst toggleTheme = () => setTheme(isDark ? 'light' : 'dark')diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex cccfa2b6..a285d9a6 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1036,6 +1036,10 @@ export const admin = {const { data } = await api.get('/admin/accounting-mode')return data},+ defaultColors: async (): Promise<{ light: string | null; dark: string | null }> => {+ const { data } = await api.get('/admin/default-colors')+ return data+ },}// Global search (powers the command palette)diff --git a/frontend/src/lib/theme-utils.ts b/frontend/src/lib/theme-utils.tsnew file mode 100644index 00000000..9340a4e3--- /dev/null+++ b/frontend/src/lib/theme-utils.ts@@ -0,0 +1,36 @@+export function setThemeBasedOnSystem(lightColor: string | null, darkColor: string | null, resolvedTheme?: string) {+ const root = document.documentElement+ const isDark = resolvedTheme === 'dark'++ const themeColor = isDark+ ? darkColor+ : lightColor++ if (themeColor) {+ root.style.setProperty('--primary', themeColor)+ root.style.setProperty('--ring', themeColor)+ root.style.setProperty('--sidebar-primary', themeColor)++ const mixBase = isDark ? 'black' : 'white'+ const contrastBase = isDark ? 'white' : 'black'++ const accentBg = `color-mix(in srgb, ${themeColor}, ${mixBase} 90%)`+ const mutedBg = `color-mix(in srgb, ${themeColor}, ${mixBase} 94%)`+ root.style.setProperty('--accent', accentBg)+ root.style.setProperty('--sidebar-accent', accentBg)+ root.style.setProperty('--muted', mutedBg)++ const accentFg = `color-mix(in srgb, ${themeColor}, ${contrastBase} 20%)`+ root.style.setProperty('--accent-foreground', accentFg)+ root.style.setProperty('--sidebar-accent-foreground', accentFg)+ } else {+ root.style.removeProperty('--primary')+ root.style.removeProperty('--ring')+ root.style.removeProperty('--sidebar-primary')+ root.style.removeProperty('--accent')+ root.style.removeProperty('--accent-foreground')+ root.style.removeProperty('--muted')+ root.style.removeProperty('--sidebar-accent')+ root.style.removeProperty('--sidebar-accent-foreground')+ }+}\ No newline at end of filediff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 3568216a..36249559 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -557,7 +557,11 @@"theme": "Theme","themeLight": "Light","themeDark": "Dark",- "themeSystem": "System"+ "themeSystem": "System",+ "customization": "Customization",+ "themeColor": "Theme color",+ "lightMode": "Light mode",+ "darkMode": "Dark mode"},"budgets": {"title": "Budgets",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 365f1f83..c8c237f7 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -555,7 +555,11 @@"theme": "Tema","themeLight": "Claro","themeDark": "Oscuro",- "themeSystem": "Sistema"+ "themeSystem": "Sistema",+ "customization": "Personalización",+ "themeColor": "Color del tema",+ "lightMode": "Modo claro",+ "darkMode": "Modo oscuro"},"budgets": {"title": "Presupuestos",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 0fd46ed1..ebc5d747 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -557,7 +557,11 @@"theme": "Tema","themeLight": "Claro","themeDark": "Escuro",- "themeSystem": "Sistema"+ "themeSystem": "Sistema",+ "customization": "Personalização",+ "themeColor": "Cor do tema",+ "lightMode": "Modo claro",+ "darkMode": "Modo escuro"},"budgets": {"title": "Orçamentos",diff --git a/frontend/src/pages/admin/settings.tsx b/frontend/src/pages/admin/settings.tsxindex 85c5cae3..e51390f5 100644--- a/frontend/src/pages/admin/settings.tsx+++ b/frontend/src/pages/admin/settings.tsx@@ -1,5 +1,6 @@import { useState } from 'react'import { useTranslation } from 'react-i18next'+import { useTheme } from 'next-themes'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { admin as adminApi, currencies as currenciesApi } from '@/lib/api'import { useAuth } from '@/contexts/auth-context'@@ -26,13 +27,15 @@ import {SelectValue,} from '@/components/ui/select'import { PageHeader } from '@/components/page-header'-import { Search, Plus, Trash2, Shield, ShieldOff, UserCog, Users, Scale, Tag } from 'lucide-react'+import { setThemeBasedOnSystem } from '@/lib/theme-utils'+import { Search, Plus, Trash2, Shield, ShieldOff, UserCog, Users, Scale, Tag, Palette, Save } from 'lucide-react'import type { AdminUser } from '@/types'export default function AdminSettingsPage() {const { t } = useTranslation()const { user: currentUser } = useAuth()const queryClient = useQueryClient()+ const { resolvedTheme } = useTheme()const [search, setSearch] = useState('')const [createOpen, setCreateOpen] = useState(false)@@ -51,6 +54,11 @@ export default function AdminSettingsPage() {const [editPassword, setEditPassword] = useState('')const [showPasswordField, setShowPasswordField] = useState(false)+ const [lastSyncedLight, setLastSyncedLight] = useState<string | undefined>()+ const [lastSyncedDark, setLastSyncedDark] = useState<string | undefined>()+ const [localLight, setLocalLight] = useState<string>('#6366F1')+ const [localDark, setLocalDark] = useState<string>('#818CF8')+const { data: usersData, isLoading: usersLoading } = useQuery({queryKey: ['admin', 'users', search],queryFn: () => adminApi.listUsers({ search: search || undefined }),@@ -111,6 +119,19 @@ export default function AdminSettingsPage() {},})+ // Theme color settings+ const { data: themeColorLightSetting } = useQuery({+ queryKey: ['admin', 'settings', 'theme_color_light'],+ queryFn: () => adminApi.getSetting('theme_color_light').catch(() => null),+ retry: false,+ })++ const { data: themeColorDarkSetting } = useQuery({+ queryKey: ['admin', 'settings', 'theme_color_dark'],+ queryFn: () => adminApi.getSetting('theme_color_dark').catch(() => null),+ retry: false,+ })+// Credit card accounting mode: returns 404 when unset → defaults to "cash".const { data: ccModeSetting } = useQuery({queryKey: ['admin', 'settings', 'credit_card_accounting_mode'],@@ -158,6 +179,32 @@ export default function AdminSettingsPage() {const useProviderCats = providerCatsSetting?.value !== 'false'+ if (themeColorLightSetting?.value && themeColorLightSetting.value !== lastSyncedLight) {+ setLastSyncedLight(themeColorLightSetting.value)+ setLocalLight(themeColorLightSetting.value)+ }+ if (themeColorDarkSetting?.value && themeColorDarkSetting.value !== lastSyncedDark) {+ setLastSyncedDark(themeColorDarkSetting.value)+ setLocalDark(themeColorDarkSetting.value)+ }++ const saveColorsMutation = useMutation({+ mutationFn: async () => {+ await Promise.all([+ adminApi.updateSetting('theme_color_light', localLight),+ adminApi.updateSetting('theme_color_dark', localDark),+ ])+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['admin', 'settings'] })+ setThemeBasedOnSystem(localLight, localDark, resolvedTheme)+ toast.success(t('admin.settings.updated'))+ },+ onError: () => {+ toast.error(t('common.error'))+ },+ })+function resetCreateForm() {setFormEmail('')setFormPassword('')@@ -271,6 +318,64 @@ export default function AdminSettingsPage() {)}</div>+ {/* Theme and Customization Section */}+ <div className="grid grid-cols-1 gap-6 mb-8">+ <div className="rounded-xl border border-border/60 bg-card overflow-hidden">+ <div className="px-5 py-4 border-b border-border/40 flex items-center justify-between">+ <div className="flex items-center gap-2">+ <Palette size={15} className="text-muted-foreground" />+ <h3 className="text-sm font-semibold text-foreground">{t('settings.customization')}</h3>+ </div>+ <Button+ onClick={() => saveColorsMutation.mutate()}+ disabled={saveColorsMutation.isPending}+ >+ <Save size={13} />+ {saveColorsMutation.isPending ? t('common.loading') : t('common.save')}+ </Button>+ </div>+ <div className="p-5 grid grid-cols-1 md:grid-cols-2 gap-6">+ {/* Light Mode Colors */}+ <div className="space-y-3">+ <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">+ {t('settings.lightMode')}+ </p>+ <div className="space-y-1.5">+ <Label className="text-xs">{t('settings.themeColor')}</Label>+ <div className="flex items-center gap-2">+ <Input+ type="color"+ className="w-12 h-9 p-1 cursor-pointer"+ value={localLight}+ onChange={(e) => setLocalLight(e.target.value)}+ />+ <span className="text-xs font-mono text-muted-foreground">{localLight}</span>+ </div>+ </div>+ </div>++ {/* Dark Mode Colors */}+ <div className="space-y-3">+ <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">+ {t('settings.darkMode')}+ </p>+ <div className="space-y-1.5">+ <Label className="text-xs">{t('settings.themeColor')}</Label>+ <div className="flex items-center gap-2">+ <Input+ type="color"+ className="w-12 h-9 p-1 cursor-pointer"+ value={localDark}+ onChange={(e) => setLocalDark(e.target.value)}+ />+ <span className="text-xs font-mono text-muted-foreground">{localDark}</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+{/* Accounting section */}<div className="rounded-xl border border-border/60 bg-card overflow-hidden mb-8"><div className="px-5 py-4 border-b border-border/40">diff --git a/frontend/src/pages/login.tsx b/frontend/src/pages/login.tsxindex 641d4cab..1102962d 100644--- a/frontend/src/pages/login.tsx+++ b/frontend/src/pages/login.tsx@@ -9,11 +9,14 @@ import { Label } from '@/components/ui/label'import { Card, CardContent, CardFooter } from '@/components/ui/card'import { ShellLogo } from '@/components/shell-logo'import type { AxiosError } from 'axios'+import { useTheme } from 'next-themes'+import { setThemeBasedOnSystem } from '@/lib/theme-utils'export default function LoginPage() {const { t } = useTranslation()const { login, verify2fa, token } = useAuth()const navigate = useNavigate()+ const { resolvedTheme } = useTheme()const [email, setEmail] = useState('')const [password, setPassword] = useState('')const [error, setError] = useState('')@@ -38,7 +41,10 @@ export default function LoginPage() {adminApi.registrationStatus().then(({ enabled }) => {setRegistrationEnabled(enabled)}).catch(() => {})- }, [navigate, token])+ adminApi.defaultColors().then(({ light, dark }) => {+ setThemeBasedOnSystem(light, dark, resolvedTheme)+ }).catch(() => {})+ }, [navigate, token, resolvedTheme])const handleSubmit = async (e: React.FormEvent) => {e.preventDefault()diff --git a/frontend/src/pages/register.tsx b/frontend/src/pages/register.tsxindex c16f5bab..3f5b165b 100644--- a/frontend/src/pages/register.tsx+++ b/frontend/src/pages/register.tsx@@ -1,6 +1,7 @@import { useState, useEffect } from 'react'import { Link, useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'+import { useTheme } from 'next-themes'import { useAuth } from '@/contexts/auth-context'import { admin as adminApi } from '@/lib/api'import { resolveSupportedLang } from '@/lib/i18n'@@ -10,12 +11,14 @@ import { Label } from '@/components/ui/label'import { Card, CardContent, CardFooter } from '@/components/ui/card'import { CurrencySelect } from '@/components/currency-select'import { ShellLogo } from '@/components/shell-logo'+import { setThemeBasedOnSystem } from '@/lib/theme-utils'import type { AxiosError } from 'axios'export default function RegisterPage() {const { t, i18n } = useTranslation()const { register } = useAuth()const navigate = useNavigate()+ const { resolvedTheme } = useTheme()const [email, setEmail] = useState('')const [password, setPassword] = useState('')const [confirmPassword, setConfirmPassword] = useState('')@@ -27,7 +30,10 @@ export default function RegisterPage() {adminApi.registrationStatus().then(({ enabled }) => {if (!enabled) navigate('/login', { replace: true })}).catch(() => {})- }, [navigate])+ adminApi.defaultColors().then(({ light, dark }) => {+ setThemeBasedOnSystem(light, dark, resolvedTheme)+ }).catch(() => {})+ }, [navigate, resolvedTheme])const handleSubmit = async (e: React.FormEvent) => {e.preventDefault()