Support multiple named, saved custom themes per user

Replaces the single custom_theme_colors blob (one palette per user) with
a proper CustomTheme table -- users can now save, name, and switch
between as many custom palettes as they like, not just one.

Data model: users.active_custom_theme_id references whichever saved
CustomTheme (if any) is currently active; theme='custom' + that id
together determine what's rendered. The migration data-migrates any
already-saved single palette into a named CustomTheme row on upgrade,
and best-effort backfills the active one back into the old column shape
on downgrade.

New endpoints under /api/custom-themes: list, create, rename/recolor,
delete (falls back the user to a preset if the deleted theme was
active, so the two theme columns can never disagree), and activate.
UserRead.active_custom_theme is only populated when theme == 'custom'
even though the DB deliberately keeps the id set while a preset is
active, so switching to a preset and back doesn't lose the saved
palette.

ProfileModal now lists saved themes as swatches (click to activate,
pencil to edit -- active or not, trash to delete with a confirm), plus
a "+ New" button that creates, activates, and opens the editor for a
fresh theme immediately.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-17 07:53:05 -06:00
co-authored by Claude Sonnet 5
parent 73020fa39f
commit bd3e621e9f
21 changed files with 972 additions and 203 deletions
+4 -3
View File
@@ -1,6 +1,7 @@
from sqlalchemy import or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.models import User
from app.schemas.user import UserCreate
@@ -40,9 +41,9 @@ async def authenticate_user(
db: AsyncSession, username_or_email: str, password: str
) -> User:
result = await db.execute(
select(User).where(
or_(User.username == username_or_email, User.email == username_or_email)
)
select(User)
.where(or_(User.username == username_or_email, User.email == username_or_email))
.options(selectinload(User.active_custom_theme))
)
user = result.scalar_one_or_none()
if user is None or not verify_password(password, user.password_hash):
@@ -0,0 +1,107 @@
import uuid
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import CustomTheme, User
from app.schemas.custom_theme import CustomThemeColors
# Sane cap, not a hard product requirement -- keeps the swatch list from
# growing unbounded and matches this app's generally modest per-user scale
# (self-hosted, small groups) elsewhere.
MAX_CUSTOM_THEMES_PER_USER = 20
class CustomThemeNotFoundError(Exception):
pass
class CustomThemeLimitReachedError(Exception):
pass
async def list_custom_themes(db: AsyncSession, user_id: uuid.UUID) -> list[CustomTheme]:
result = await db.execute(
select(CustomTheme)
.where(CustomTheme.user_id == user_id)
.order_by(CustomTheme.created_at)
)
return list(result.scalars().all())
async def create_custom_theme(
db: AsyncSession, user_id: uuid.UUID, name: str, colors: CustomThemeColors
) -> CustomTheme:
count = await db.scalar(
select(func.count()).select_from(CustomTheme).where(CustomTheme.user_id == user_id)
)
if count >= MAX_CUSTOM_THEMES_PER_USER:
raise CustomThemeLimitReachedError()
theme = CustomTheme(user_id=user_id, name=name, colors=colors.model_dump())
db.add(theme)
await db.commit()
await db.refresh(theme)
return theme
async def _get_owned_theme(db: AsyncSession, user_id: uuid.UUID, theme_id: uuid.UUID) -> CustomTheme:
theme = await db.get(CustomTheme, theme_id)
if theme is None or theme.user_id != user_id:
raise CustomThemeNotFoundError()
return theme
async def update_custom_theme(
db: AsyncSession,
user_id: uuid.UUID,
theme_id: uuid.UUID,
name: str | None,
colors: CustomThemeColors | None,
) -> CustomTheme:
theme = await _get_owned_theme(db, user_id, theme_id)
if name is not None:
theme.name = name
if colors is not None:
theme.colors = colors.model_dump()
await db.commit()
await db.refresh(theme)
return theme
async def delete_custom_theme(db: AsyncSession, user_id: uuid.UUID, theme_id: uuid.UUID) -> None:
theme = await _get_owned_theme(db, user_id, theme_id)
user = await db.get(User, user_id)
# A deleted-but-still-active theme would otherwise leave theme='custom'
# pointing at nothing -- fall back to a preset so the two columns can
# never disagree about what's actually being displayed.
if user.active_custom_theme_id == theme.id:
user.active_custom_theme_id = None
# Keep the relationship attribute in sync too, not just the raw FK
# column -- if `user` is already identity-mapped in this session
# (e.g. a later db.get() in the same request/connection returns the
# same Python object rather than re-querying), only the FK column
# being updated would leave .active_custom_theme still pointing at
# the object we're about to delete below.
user.active_custom_theme = None
user.theme = "dark"
# Flush the FK-clearing UPDATE before the DELETE below -- setting
# the raw *_id column directly (not the relationship attribute)
# doesn't register with SQLAlchemy's automatic flush-order
# dependency detection, so without this the DELETE can be sent
# first and trip the foreign key constraint.
await db.flush()
await db.delete(theme)
await db.commit()
async def activate_custom_theme(db: AsyncSession, user_id: uuid.UUID, theme_id: uuid.UUID) -> None:
theme = await _get_owned_theme(db, user_id, theme_id)
user = await db.get(User, user_id)
user.theme = "custom"
user.active_custom_theme_id = theme_id
# See delete_custom_theme's comment -- keep the relationship attribute
# in sync too, in case `user` is already identity-mapped elsewhere in
# this session.
user.active_custom_theme = theme
await db.commit()
+4 -1
View File
@@ -3,6 +3,7 @@ from datetime import datetime, timezone
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.models import PasswordReset, User
from app.security import hash_password, hash_token, verify_password
@@ -70,7 +71,9 @@ async def validate_reset_token(db: AsyncSession, token: str) -> None:
async def complete_password_reset(db: AsyncSession, token: str, new_password: str) -> User:
reset = await _get_valid_reset(db, token)
user = await db.get(User, reset.user_id)
user = await db.get(
User, reset.user_id, options=[selectinload(User.active_custom_theme)]
)
user.password_hash = hash_password(new_password)
reset.used = True
await db.commit()