feat(mangas): per-field sort options + direction toggle on the catalog (0.88.0)

Replace the two-option `ListSort` enum with an orthogonal sort field
(created/updated/title/author, default updated) and direction
(asc/desc, default desc). The catalog now defaults to last-updated-first
and lets the user order by any field in either direction.

Backend builds ORDER BY from the enums only (no injection seam), with a
NULLS-LAST author subquery and a stable id tie-break. Frontend adds a
direction toggle with per-field defaults (dates desc, text asc) and
labels (Newest/Oldest vs A->Z/Z->A), reusing SegmentedControl; URL state
omits the per-field defaults and validates on hydrate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-06-24 21:39:12 +02:00
parent 93b7e451bf
commit 1079a0151a
10 changed files with 348 additions and 64 deletions

2
backend/Cargo.lock generated
View File

@@ -1517,7 +1517,7 @@ checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
[[package]]
name = "mangalord"
version = "0.87.26"
version = "0.88.0"
dependencies = [
"anyhow",
"argon2",

View File

@@ -1,6 +1,6 @@
[package]
name = "mangalord"
version = "0.87.26"
version = "0.88.0"
edition = "2021"
default-run = "mangalord"

View File

@@ -52,7 +52,9 @@ pub struct ListParams {
#[serde(default)]
pub offset: i64,
#[serde(default)]
pub sort: repo::manga::ListSort,
pub sort: repo::manga::SortField,
#[serde(default)]
pub order: repo::manga::SortOrder,
}
fn default_limit() -> i64 {
@@ -105,6 +107,7 @@ async fn list(
limit,
offset,
sort: params.sort,
order: params.order,
};
let (items, total) = repo::manga::list_cards(&state.db, &q).await?;
Ok(Json(PagedResponse::with_total(items, limit, offset, total)))

View File

@@ -18,14 +18,31 @@ use crate::repo;
pub const STATUSES: &[&str] = &["ongoing", "completed"];
pub const DEFAULT_STATUS: &str = "ongoing";
/// Which column the listing is ordered by. The direction lives in a separate
/// [`SortOrder`] so any field can be sorted either way.
#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ListSort {
/// Newest first (default).
pub enum SortField {
/// Creation time.
Created,
/// Last-modified time (default — "last updated first" pairs with `Desc`).
#[default]
Recent,
/// A→Z by title (case-insensitive).
Updated,
/// Title (case-insensitive).
Title,
/// Alphabetically-first attached author (case-insensitive); authorless
/// mangas sort last regardless of direction.
Author,
}
/// Sort direction. Defaults to descending so the default listing
/// (`Updated`/`Desc`) shows the most recently updated mangas first.
#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SortOrder {
Asc,
#[default]
Desc,
}
#[derive(Debug, Clone, Default)]
@@ -42,7 +59,8 @@ pub struct ListQuery {
pub cw_exclude: Vec<String>,
pub limit: i64,
pub offset: i64,
pub sort: ListSort,
pub sort: SortField,
pub order: SortOrder,
}
/// Single source of truth for the `mangas` columns that hydrate a [`Manga`],
@@ -134,12 +152,31 @@ const FILTER_WHERE: &str = r#"
/// and 0009_manga_metadata.sql) keep both queries cheap as the library
/// grows.
pub async fn list(pool: &PgPool, query: &ListQuery) -> AppResult<(Vec<Manga>, i64)> {
// `order_by` is interpolated from a hard-coded enum, never from request
// input, so this is not a SQL injection seam.
let order_by = match query.sort {
ListSort::Recent => "created_at DESC, id",
ListSort::Title => "lower(title) ASC, id",
// Both `col` and `dir` are interpolated from hard-coded enums, never from
// request input, so this is not a SQL injection seam. `NULLS LAST` keeps
// authorless mangas out of the way in both directions, and the trailing
// `id` is a stable tie-break that keeps pagination deterministic across
// rows with equal sort keys.
let col = match query.sort {
SortField::Created => "created_at",
SortField::Updated => "updated_at",
SortField::Title => "lower(title)",
// Sorts on the alphabetically-first attached author. As an ORDER BY
// key this correlated subquery is evaluated per filter-matching row
// before LIMIT applies, so it scales worse than the indexed date/title
// sorts — revisit with a LATERAL join or precomputed sort-name column
// if the library grows large.
SortField::Author => {
"(SELECT min(lower(a.name)) \
FROM manga_authors ma JOIN authors a ON a.id = ma.author_id \
WHERE ma.manga_id = mangas.id)"
}
};
let dir = match query.order {
SortOrder::Asc => "ASC",
SortOrder::Desc => "DESC",
};
let order_by = format!("{col} {dir} NULLS LAST, id");
let search = query.search.as_deref();
let status = query.status.as_deref();

View File

@@ -11,6 +11,53 @@ fn metadata(title: &str) -> serde_json::Value {
json!({ "title": title })
}
/// Collect the `title` field of every item in a list response, in order.
fn title_list(body: &serde_json::Value) -> Vec<&str> {
body["items"]
.as_array()
.unwrap()
.iter()
.map(|m| m["title"].as_str().unwrap())
.collect()
}
/// Create a manga via the upload API, asserting it succeeded.
async fn seed(app: &axum::Router, cookie: &str, title: &str) {
let resp = app
.clone()
.oneshot(common::post_multipart_with_cookie(
"/api/v1/mangas",
MultipartBuilder::new().add_json("metadata", json!({ "title": title })),
cookie,
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED, "seed({title}) failed");
}
/// Pin a manga's `created_at` to an explicit RFC3339 instant so time-based
/// ordering assertions don't depend on insert timing.
async fn set_created_at(pool: &PgPool, title: &str, when: &str) {
let ts: chrono::DateTime<chrono::Utc> = when.parse().unwrap();
sqlx::query("UPDATE mangas SET created_at = $1 WHERE title = $2")
.bind(ts)
.bind(title)
.execute(pool)
.await
.unwrap();
}
/// Pin a manga's `updated_at` to an explicit RFC3339 instant.
async fn set_updated_at(pool: &PgPool, title: &str, when: &str) {
let ts: chrono::DateTime<chrono::Utc> = when.parse().unwrap();
sqlx::query("UPDATE mangas SET updated_at = $1 WHERE title = $2")
.bind(ts)
.bind(title)
.execute(pool)
.await
.unwrap();
}
#[sqlx::test(migrations = "./migrations")]
async fn list_is_empty_initially(pool: PgPool) {
let h = common::harness(pool);
@@ -103,21 +150,137 @@ async fn list_sort_title_orders_alphabetically(pool: PgPool) {
.unwrap();
}
// Title sort now requires an explicit direction; the wire default is
// `desc`, so A→Z needs `order=asc`.
let resp = h
.app
.oneshot(common::get("/api/v1/mangas?sort=title"))
.oneshot(common::get("/api/v1/mangas?sort=title&order=asc"))
.await
.unwrap();
let body = common::body_json(resp).await;
let titles: Vec<&str> = body["items"]
.as_array()
.unwrap()
.iter()
.map(|m| m["title"].as_str().unwrap())
.collect();
let titles = title_list(&body);
assert_eq!(titles, vec!["Berserk", "One Piece", "Vinland Saga"]);
}
#[sqlx::test(migrations = "./migrations")]
async fn list_sort_title_desc_orders_reverse_alphabetically(pool: PgPool) {
let h = common::harness(pool);
let (_, cookie) = common::register_user(&h.app).await;
for title in ["Vinland Saga", "Berserk", "One Piece"] {
seed(&h.app, &cookie, title).await;
}
let resp = h
.app
.oneshot(common::get("/api/v1/mangas?sort=title&order=desc"))
.await
.unwrap();
let body = common::body_json(resp).await;
let titles = title_list(&body);
assert_eq!(titles, vec!["Vinland Saga", "One Piece", "Berserk"]);
}
#[sqlx::test(migrations = "./migrations")]
async fn list_default_sort_is_updated_desc(pool: PgPool) {
let h = common::harness(pool.clone());
let (_, cookie) = common::register_user(&h.app).await;
for title in ["Alpha", "Bravo", "Charlie"] {
seed(&h.app, &cookie, title).await;
}
// Pin explicit, distinct update times so the default ordering is
// deterministic regardless of insert timing. Bravo is the most recently
// updated and must appear first under the default (updated DESC).
set_updated_at(&pool, "Alpha", "2020-01-01T00:00:00Z").await;
set_updated_at(&pool, "Bravo", "2023-01-01T00:00:00Z").await;
set_updated_at(&pool, "Charlie", "2021-01-01T00:00:00Z").await;
// No sort/order params — exercises the default.
let resp = h.app.oneshot(common::get("/api/v1/mangas")).await.unwrap();
let body = common::body_json(resp).await;
let titles = title_list(&body);
assert_eq!(titles, vec!["Bravo", "Charlie", "Alpha"]);
}
#[sqlx::test(migrations = "./migrations")]
async fn list_sort_created_orders_by_creation_time(pool: PgPool) {
let h = common::harness(pool.clone());
let (_, cookie) = common::register_user(&h.app).await;
for title in ["Alpha", "Bravo", "Charlie"] {
seed(&h.app, &cookie, title).await;
}
set_created_at(&pool, "Alpha", "2020-01-01T00:00:00Z").await;
set_created_at(&pool, "Bravo", "2023-01-01T00:00:00Z").await;
set_created_at(&pool, "Charlie", "2021-01-01T00:00:00Z").await;
// Newest-created first.
let resp = h
.app
.clone()
.oneshot(common::get("/api/v1/mangas?sort=created&order=desc"))
.await
.unwrap();
let body = common::body_json(resp).await;
assert_eq!(title_list(&body), vec!["Bravo", "Charlie", "Alpha"]);
// Ascending is the exact reverse.
let resp = h
.app
.oneshot(common::get("/api/v1/mangas?sort=created&order=asc"))
.await
.unwrap();
let body = common::body_json(resp).await;
assert_eq!(title_list(&body), vec!["Alpha", "Charlie", "Bravo"]);
}
#[sqlx::test(migrations = "./migrations")]
async fn list_sort_author_orders_by_author_name_nulls_last(pool: PgPool) {
let h = common::harness(pool);
let (_, cookie) = common::register_user(&h.app).await;
// Author order is deliberately scrambled relative to title order so the
// assertion can't pass by accidentally sorting on title.
for (title, authors) in [
("Akira", json!(["Beta Author"])),
("Boku", json!(["Alpha Author"])),
("Chi", json!(["Gamma Author"])),
("NoAuthor", json!([])),
] {
let _ = h
.app
.clone()
.oneshot(common::post_multipart_with_cookie(
"/api/v1/mangas",
MultipartBuilder::new()
.add_json("metadata", json!({ "title": title, "authors": authors })),
&cookie,
))
.await
.unwrap();
}
// Ascending by author name; the authorless manga sorts last (NULLS LAST).
let resp = h
.app
.clone()
.oneshot(common::get("/api/v1/mangas?sort=author&order=asc"))
.await
.unwrap();
let body = common::body_json(resp).await;
assert_eq!(title_list(&body), vec!["Boku", "Akira", "Chi", "NoAuthor"]);
// Descending flips the authored mangas but keeps the authorless one last.
let resp = h
.app
.oneshot(common::get("/api/v1/mangas?sort=author&order=desc"))
.await
.unwrap();
let body = common::body_json(resp).await;
assert_eq!(title_list(&body), vec!["Chi", "Akira", "Boku", "NoAuthor"]);
}
#[sqlx::test(migrations = "./migrations")]
async fn search_reflects_filtered_total(pool: PgPool) {
let h = common::harness(pool);