Add per-user gallery favourites with heart toggle

Adds a favourites table, API endpoints (list/add/remove), and UI
integration: heart icons on gallery cards (home page) and in the
gallery viewer header, with a favourites section on the home page.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-27 12:48:58 +02:00
parent 1bf3ac1303
commit fb56428494
12 changed files with 316 additions and 24 deletions

View File

@@ -0,0 +1,59 @@
use axum::{
extract::{Path, State},
http::StatusCode,
routing::get,
Extension, Json, Router,
};
use crate::{
error::{ApiError, ApiResult},
middleware::AuthUser,
routes::gallery::GalleryResponse,
state::AppState,
};
pub fn router() -> Router<AppState> {
Router::new()
.route("/", get(list_favourites))
.route("/ids", get(list_favourite_ids))
.route("/{id}", axum::routing::put(add_favourite).delete(remove_favourite))
}
async fn list_favourites(
State(state): State<AppState>,
Extension(auth): Extension<AuthUser>,
) -> ApiResult<Json<Vec<GalleryResponse>>> {
let galleries = rbv_data::favourite::list_favourite_galleries(&state.pool, auth.id).await?;
Ok(Json(galleries.into_iter().map(Into::into).collect()))
}
async fn list_favourite_ids(
State(state): State<AppState>,
Extension(auth): Extension<AuthUser>,
) -> ApiResult<Json<Vec<String>>> {
let ids = rbv_data::favourite::list_favourite_ids(&state.pool, auth.id).await?;
Ok(Json(ids.into_iter().map(|id| id.to_hex()).collect()))
}
async fn add_favourite(
State(state): State<AppState>,
Extension(auth): Extension<AuthUser>,
Path(id): Path<String>,
) -> ApiResult<StatusCode> {
let bytes = rbv_hash::from_hex(&id)
.map_err(|_| ApiError::bad_request("invalid gallery id"))?;
let gid = rbv_entity::GalleryId(bytes);
rbv_data::favourite::add_favourite(&state.pool, auth.id, &gid).await?;
Ok(StatusCode::NO_CONTENT)
}
async fn remove_favourite(
State(state): State<AppState>,
Extension(auth): Extension<AuthUser>,
Path(id): Path<String>,
) -> ApiResult<StatusCode> {
let bytes = rbv_hash::from_hex(&id)
.map_err(|_| ApiError::bad_request("invalid gallery id"))?;
let gid = rbv_entity::GalleryId(bytes);
rbv_data::favourite::remove_favourite(&state.pool, auth.id, &gid).await?;
Ok(StatusCode::NO_CONTENT)
}

View File

@@ -4,6 +4,7 @@ pub mod person;
pub mod face;
pub mod search;
pub mod auth;
pub mod favourite;
use axum::Router;
use crate::state::AppState;
@@ -14,9 +15,10 @@ pub fn protected_routes() -> Router<AppState> {
.nest("/api/galleries", gallery::router())
.nest("/api/images", image::router())
.nest("/api/persons", person::router())
.nest("/api/faces", face::router())
.nest("/api/search", search::router())
.nest("/api/auth", auth::me_router())
.nest("/api/faces", face::router())
.nest("/api/search", search::router())
.nest("/api/favourites", favourite::router())
.nest("/api/auth", auth::me_router())
}
/// Routes that are always public (login, register, logout).

View File

@@ -0,0 +1,56 @@
use anyhow::Result;
use sqlx::{PgPool, Row};
use uuid::Uuid;
use rbv_entity::{Gallery, GalleryId};
pub async fn add_favourite(pool: &PgPool, user_id: Uuid, gallery_id: &GalleryId) -> Result<()> {
sqlx::query(
"INSERT INTO favourites (user_id, gallery_id) VALUES ($1, $2) ON CONFLICT DO NOTHING",
)
.bind(user_id)
.bind(gallery_id.as_bytes())
.execute(pool)
.await?;
Ok(())
}
pub async fn remove_favourite(pool: &PgPool, user_id: Uuid, gallery_id: &GalleryId) -> Result<()> {
sqlx::query("DELETE FROM favourites WHERE user_id = $1 AND gallery_id = $2")
.bind(user_id)
.bind(gallery_id.as_bytes())
.execute(pool)
.await?;
Ok(())
}
pub async fn list_favourite_galleries(pool: &PgPool, user_id: Uuid) -> Result<Vec<Gallery>> {
let rows = sqlx::query(
r#"
SELECT g.id, g.source_id, g.collection, g.source_name, g.source_url, g.subjects, g.tags, g.path
FROM favourites f
JOIN galleries g ON g.id = f.gallery_id
WHERE f.user_id = $1
ORDER BY f.created_at DESC
"#,
)
.bind(user_id)
.fetch_all(pool)
.await?;
Ok(rows.iter().map(crate::gallery::row_to_gallery).collect())
}
pub async fn list_favourite_ids(pool: &PgPool, user_id: Uuid) -> Result<Vec<GalleryId>> {
let rows = sqlx::query("SELECT gallery_id FROM favourites WHERE user_id = $1")
.bind(user_id)
.fetch_all(pool)
.await?;
Ok(rows
.iter()
.map(|r| {
let bytes: Vec<u8> = r.get("gallery_id");
GalleryId(bytes.try_into().expect("32-byte id"))
})
.collect())
}

View File

@@ -62,7 +62,7 @@ pub async fn random_galleries(pool: &PgPool, count: i64) -> Result<Vec<Gallery>>
Ok(rows.iter().map(row_to_gallery).collect())
}
fn row_to_gallery(r: &sqlx::postgres::PgRow) -> Gallery {
pub(crate) fn row_to_gallery(r: &sqlx::postgres::PgRow) -> Gallery {
let id_bytes: Vec<u8> = r.get("id");
Gallery {
id: GalleryId(id_bytes.try_into().expect("32-byte id")),

View File

@@ -5,6 +5,7 @@ pub mod face;
pub mod person;
pub mod clip;
pub mod user;
pub mod favourite;
pub use pool::{connect, run_migrations};
pub use sqlx::PgPool;

View File

@@ -0,0 +1,8 @@
CREATE TABLE favourites (
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
gallery_id BYTEA NOT NULL REFERENCES galleries(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, gallery_id)
);
CREATE INDEX idx_favourites_user ON favourites(user_id);

View File

@@ -120,6 +120,18 @@ export const getPersonGalleries = (id: string, page = 1, perPage = 24) =>
export const mergePersons = (target: string, source: string) =>
request<void>('/persons/merge', { method: 'POST', body: JSON.stringify({ target, source }) })
// ── Favourites ───────────────────────────────────────────────────────────────
export const listFavourites = () => request<Gallery[]>('/favourites')
export const listFavouriteIds = () => request<string[]>('/favourites/ids')
export const addFavourite = (id: string) =>
request<void>(`/favourites/${id}`, { method: 'PUT' })
export const removeFavourite = (id: string) =>
request<void>(`/favourites/${id}`, { method: 'DELETE' })
// ── Search ────────────────────────────────────────────────────────────────────
export interface SearchResult {

View File

@@ -10,7 +10,8 @@
"toggle": "Toggle theme"
},
"home": {
"refresh": "Refresh"
"refresh": "Refresh",
"favourites": "Favourites"
},
"login": {
"title": "Sign in",

View File

@@ -135,6 +135,10 @@ input:focus {
background: var(--colour-surface);
}
.card-thumb-wrap {
position: relative;
}
.card-label {
padding: 0.5rem 0.75rem;
font-size: 0.8rem;
@@ -144,6 +148,41 @@ input:focus {
text-overflow: ellipsis;
}
.fav-btn {
position: absolute;
top: 0.4rem;
right: 0.4rem;
background: rgba(0, 0, 0, 0.45);
border: none;
border-radius: var(--radius-round);
width: 2rem;
height: 2rem;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
font-size: 1.1rem;
color: #fff;
transition: background 0.15s, transform 0.15s;
line-height: 1;
}
.fav-btn:hover {
background: rgba(0, 0, 0, 0.65);
transform: scale(1.1);
}
.fav-btn.active {
color: var(--colour-danger);
}
.section-title {
font-size: 1.1rem;
font-weight: 600;
margin: 2rem 0 0.75rem;
color: var(--colour-text);
}
.tag {
display: inline-block;
padding: 0.2rem 0.5rem;

View File

@@ -20,6 +20,30 @@
flex: 1;
}
.gallery-fav-btn {
background: none;
border: none;
font-size: 1.3rem;
cursor: pointer;
color: var(--colour-text-muted);
line-height: 1;
padding: 0.25rem;
transition: color 0.15s, transform 0.15s;
}
.gallery-fav-btn:hover {
transform: scale(1.15);
}
.gallery-fav-btn.active {
color: var(--colour-danger);
}
.gallery-fav-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.gallery-persons {
display: flex;
gap: 0.5rem;

View File

@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next'
import {
getGallery, getGalleryImages, getGalleryPersons,
imageFileUrl, thumbnailUrl,
listFavouriteIds, addFavourite, removeFavourite,
} from '../api/client'
import type { Gallery as GalleryType, GalleryImage, Person } from '../api/client'
import './Gallery.css'
@@ -15,6 +16,8 @@ export function Gallery() {
const [images, setImages] = useState<GalleryImage[]>([])
const [current, setCurrent] = useState(0)
const [persons, setPersons] = useState<Person[]>([])
const [isFav, setIsFav] = useState(false)
const [favBusy, setFavBusy] = useState(false)
const [zoom, setZoom] = useState(1)
const [offset, setOffset] = useState({ x: 0, y: 0 })
const [dragging, setDragging] = useState(false)
@@ -26,6 +29,9 @@ export function Gallery() {
if (!id) return
getGallery(id).then(setGallery)
getGalleryImages(id).then(imgs => { setImages(imgs); setCurrent(0) })
listFavouriteIds()
.then(ids => setIsFav(ids.includes(id)))
.catch(() => setIsFav(false))
}, [id])
// Reset zoom/pan and scroll active thumbnail into view
@@ -45,6 +51,22 @@ export function Gallery() {
getGalleryPersons(id).then(setPersons).catch(() => setPersons([]))
}, [id])
const toggleFav = useCallback(async () => {
if (favBusy || !id) return
setFavBusy(true)
try {
if (isFav) {
await removeFavourite(id)
setIsFav(false)
} else {
await addFavourite(id)
setIsFav(true)
}
} finally {
setFavBusy(false)
}
}, [id, isFav, favBusy])
const prev = useCallback(() => setCurrent(c => (c - 1 + images.length) % images.length), [images.length])
const next = useCallback(() => setCurrent(c => (c + 1) % images.length), [images.length])
@@ -114,6 +136,14 @@ export function Gallery() {
<div className="gallery-page">
<div className="gallery-header">
<div className="gallery-title">{gallery.source_name || gallery.collection}</div>
<button
className={`gallery-fav-btn${isFav ? ' active' : ''}`}
onClick={toggleFav}
disabled={favBusy}
aria-label={isFav ? 'Remove from favourites' : 'Add to favourites'}
>
{isFav ? '♥' : '♡'}
</button>
{persons.length > 0 && (
<div className="gallery-persons">
{persons.map(p => (

View File

@@ -1,7 +1,10 @@
import { useEffect, useState, useCallback } from 'react'
import { Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { randomGalleries, getGalleryImages, thumbnailUrl } from '../api/client'
import {
randomGalleries, getGalleryImages, thumbnailUrl,
listFavouriteIds, listFavourites, addFavourite, removeFavourite,
} from '../api/client'
import type { Gallery, GalleryImage } from '../api/client'
interface GalleryThumb {
@@ -13,18 +16,33 @@ export function Home() {
const { t } = useTranslation()
const [items, setItems] = useState<GalleryThumb[]>([])
const [loading, setLoading] = useState(true)
const [favIds, setFavIds] = useState<Set<string>>(new Set())
const [favItems, setFavItems] = useState<GalleryThumb[]>([])
const [toggling, setToggling] = useState<Set<string>>(new Set())
const loadThumbs = async (galleries: Gallery[]): Promise<GalleryThumb[]> =>
Promise.all(
galleries.map(async (gallery): Promise<GalleryThumb> => {
const images = await getGalleryImages(gallery.id).catch(() => [] as GalleryImage[])
return { gallery, image: images[0] ?? null }
})
)
const load = useCallback(async () => {
setLoading(true)
try {
const galleries = await randomGalleries(12)
const thumbs = await Promise.all(
galleries.map(async (gallery): Promise<GalleryThumb> => {
const images = await getGalleryImages(gallery.id).catch(() => [] as GalleryImage[])
return { gallery, image: images[0] ?? null }
})
)
const [galleries, ids, favGalleries] = await Promise.all([
randomGalleries(12),
listFavouriteIds().catch(() => [] as string[]),
listFavourites().catch(() => [] as Gallery[]),
])
const [thumbs, favThumbs] = await Promise.all([
loadThumbs(galleries),
loadThumbs(favGalleries),
])
setItems(thumbs)
setFavIds(new Set(ids))
setFavItems(favThumbs)
} finally {
setLoading(false)
}
@@ -32,6 +50,46 @@ export function Home() {
useEffect(() => { load() }, [load])
const toggleFav = async (galleryId: string) => {
if (toggling.has(galleryId)) return
setToggling(prev => new Set(prev).add(galleryId))
try {
const isFav = favIds.has(galleryId)
if (isFav) {
await removeFavourite(galleryId)
setFavIds(prev => { const next = new Set(prev); next.delete(galleryId); return next })
setFavItems(prev => prev.filter(f => f.gallery.id !== galleryId))
} else {
await addFavourite(galleryId)
setFavIds(prev => new Set(prev).add(galleryId))
const existing = items.find(i => i.gallery.id === galleryId)
if (existing) setFavItems(prev => [existing, ...prev])
}
} finally {
setToggling(prev => { const next = new Set(prev); next.delete(galleryId); return next })
}
}
const renderCard = ({ gallery, image }: GalleryThumb) => (
<Link key={gallery.id} to={`/gallery/${gallery.id}`} className="card" style={{ textDecoration: 'none' }}>
<div className="card-thumb-wrap">
{image
? <img className="card-thumb" src={thumbnailUrl(image.image_id)} alt={image.filename} loading="lazy" />
: <div className="card-thumb" />
}
<button
className={`fav-btn${favIds.has(gallery.id) ? ' active' : ''}`}
onClick={(e) => { e.preventDefault(); e.stopPropagation(); toggleFav(gallery.id) }}
disabled={toggling.has(gallery.id)}
aria-label={favIds.has(gallery.id) ? 'Remove from favourites' : 'Add to favourites'}
>
{favIds.has(gallery.id) ? '♥' : '♡'}
</button>
</div>
<div className="card-label">{gallery.source_name || gallery.collection}</div>
</Link>
)
return (
<div className="page">
<div className="home-toolbar">
@@ -42,17 +100,19 @@ export function Home() {
{loading
? <div className="loading">{t('error.loading')}</div>
: (
<div className="grid-4" style={{ marginTop: '1rem' }}>
{items.map(({ gallery, image }) => (
<Link key={gallery.id} to={`/gallery/${gallery.id}`} className="card" style={{ textDecoration: 'none' }}>
{image
? <img className="card-thumb" src={thumbnailUrl(image.image_id)} alt={image.filename} loading="lazy" />
: <div className="card-thumb" />
}
<div className="card-label">{gallery.source_name || gallery.collection}</div>
</Link>
))}
</div>
<>
<div className="grid-4" style={{ marginTop: '1rem' }}>
{items.map(renderCard)}
</div>
{favItems.length > 0 && (
<>
<h2 className="section-title">{t('home.favourites')}</h2>
<div className="grid-4">
{favItems.map(renderCard)}
</div>
</>
)}
</>
)
}
</div>