feat(mangas): per-field sort options + direction toggle on the catalog (0.88.0)
Sort the manga catalog by created / updated / title / author with an independent asc/desc direction control. An omitted `order` defaults per field (dates newest-first, text A→Z), matching the UI, so a bare `?sort=<field>` means the same thing in the browser and over the API; `sort=recent` remains a back-compat alias for `created`. - Backend: SortField/SortOrder parsed with validation (structured 422 on bad input), per-field default_order, NULLS LAST only on the nullable author key, and migration 0033 indexing mangas(updated_at DESC, id) to back the default sort and its id tie-break. - Frontend: catalog sort field + direction (SegmentedControl) on desktop and a mobile bottom sheet; pure helpers in $lib/mangaSort; keyboard-accessible direction control; visible Direction labels and a sheet "Done" button. - Tests: backend integration coverage (defaults, alias, invalid input, ascending-id tie-break), frontend unit + e2e. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -51,14 +51,58 @@ pub struct ListParams {
|
||||
pub limit: i64,
|
||||
#[serde(default)]
|
||||
pub offset: i64,
|
||||
/// Sort field: `created`, `updated` (default), `title`, or `author`.
|
||||
/// Also accepts the legacy `recent` alias (== `created`). Anything
|
||||
/// else → 422.
|
||||
#[serde(default)]
|
||||
pub sort: repo::manga::ListSort,
|
||||
pub sort: Option<String>,
|
||||
/// `asc` or `desc`. Omitted → the field's natural default
|
||||
/// (dates `desc`, text `asc`). Anything else → 422.
|
||||
#[serde(default)]
|
||||
pub order: Option<String>,
|
||||
}
|
||||
|
||||
fn default_limit() -> i64 {
|
||||
50
|
||||
}
|
||||
|
||||
/// Parse the `sort` wire value into a [`repo::manga::SortField`]. Validation
|
||||
/// and the legacy `recent` alias live here (not in serde) so unknown values
|
||||
/// return the structured 422 envelope rather than axum's plain-text
|
||||
/// `QueryRejection`, matching the rest of this handler's filters.
|
||||
fn parse_sort(raw: Option<&str>) -> AppResult<repo::manga::SortField> {
|
||||
use repo::manga::SortField;
|
||||
match raw.map(str::trim) {
|
||||
None | Some("") | Some("updated") => Ok(SortField::Updated),
|
||||
// `recent` was the pre-0.88 name for "newest created first"; keep it
|
||||
// as an alias so existing bots/scripts don't break.
|
||||
Some("created") | Some("recent") => Ok(SortField::Created),
|
||||
Some("title") => Ok(SortField::Title),
|
||||
Some("author") => Ok(SortField::Author),
|
||||
Some(other) => Err(AppError::ValidationFailed {
|
||||
message: format!(
|
||||
"sort must be one of created, updated, title, author (got {other:?})"
|
||||
),
|
||||
details: json!({ "sort": "invalid" }),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the `order` wire value. `None` means the client omitted it, so the
|
||||
/// caller applies the field's natural default. An explicit unknown value → 422.
|
||||
fn parse_order(raw: Option<&str>) -> AppResult<Option<repo::manga::SortOrder>> {
|
||||
use repo::manga::SortOrder;
|
||||
match raw.map(str::trim) {
|
||||
None | Some("") => Ok(None),
|
||||
Some("asc") => Ok(Some(SortOrder::Asc)),
|
||||
Some("desc") => Ok(Some(SortOrder::Desc)),
|
||||
Some(other) => Err(AppError::ValidationFailed {
|
||||
message: format!("order must be 'asc' or 'desc' (got {other:?})"),
|
||||
details: json!({ "order": "invalid" }),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_uuid_csv(field: &str, raw: Option<&str>) -> AppResult<Vec<Uuid>> {
|
||||
let Some(raw) = raw else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
@@ -94,6 +138,10 @@ async fn list(
|
||||
Some(s.to_string())
|
||||
}
|
||||
};
|
||||
let sort = parse_sort(params.sort.as_deref())?;
|
||||
// Omitted `order` falls back to the field's natural direction, so a bare
|
||||
// `?sort=title` reads A→Z just like the UI shows it.
|
||||
let order = parse_order(params.order.as_deref())?.unwrap_or_else(|| sort.default_order());
|
||||
let q = repo::manga::ListQuery {
|
||||
search: params.search.filter(|s| !s.trim().is_empty()),
|
||||
status,
|
||||
@@ -104,7 +152,8 @@ async fn list(
|
||||
cw_exclude: crate::api::page_tags::parse_warnings_csv(params.cw_exclude.as_deref())?,
|
||||
limit,
|
||||
offset,
|
||||
sort: params.sort,
|
||||
sort,
|
||||
order,
|
||||
};
|
||||
let (items, total) = repo::manga::list_cards(&state.db, &q).await?;
|
||||
Ok(Json(PagedResponse::with_total(items, limit, offset, total)))
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
//! handlers depend only on `sqlx::PgPool`, not on a trait object. Swap to
|
||||
//! a trait + impl if a second backend ever becomes necessary.
|
||||
|
||||
use serde::Deserialize;
|
||||
use sqlx::{PgConnection, PgExecutor, PgPool};
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -18,14 +17,43 @@ use crate::repo;
|
||||
pub const STATUSES: &[&str] = &["ongoing", "completed"];
|
||||
pub const DEFAULT_STATUS: &str = "ongoing";
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ListSort {
|
||||
/// Newest first (default).
|
||||
/// Which column the listing is ordered by. The direction lives in a separate
|
||||
/// [`SortOrder`] so any field can be sorted either way. Wire values are parsed
|
||||
/// (with validation and the legacy `recent` alias) in `api::mangas`, not via
|
||||
/// serde, so this stays a plain domain enum.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
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,
|
||||
}
|
||||
|
||||
impl SortField {
|
||||
/// The direction applied when the client omits `order`. Dates read
|
||||
/// newest-first (`Desc`); text reads A→Z (`Asc`). This mirrors the
|
||||
/// frontend's `defaultOrderFor` (see `frontend/src/lib/mangaSort.ts`) so a
|
||||
/// bare `?sort=<field>` link means the same thing to the UI and the API.
|
||||
pub fn default_order(self) -> SortOrder {
|
||||
match self {
|
||||
SortField::Created | SortField::Updated => SortOrder::Desc,
|
||||
SortField::Title | SortField::Author => SortOrder::Asc,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sort direction.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum SortOrder {
|
||||
Asc,
|
||||
#[default]
|
||||
Desc,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -42,7 +70,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`],
|
||||
@@ -130,16 +159,42 @@ const FILTER_WHERE: &str = r#"
|
||||
"#;
|
||||
|
||||
/// Returns the page of mangas matching `query` plus the unfiltered total
|
||||
/// count for the same filter. The trigram GIN indexes (see 0005_search.sql
|
||||
/// and 0009_manga_metadata.sql) keep both queries cheap as the library
|
||||
/// grows.
|
||||
/// count for the same filter. The date/title sort columns are index-backed
|
||||
/// (`mangas_created_at_idx`, `mangas_updated_at_idx`, `mangas_title_lower_idx`)
|
||||
/// and the trigram GIN indexes (0005_search.sql, 0009_manga_metadata.sql) keep
|
||||
/// the search filter 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. 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",
|
||||
};
|
||||
// Only the author key can be NULL (authorless mangas); keep those last in
|
||||
// both directions. The date/title columns are NOT NULL, so they need no
|
||||
// NULLS clause — and omitting it lets a reverse index scan satisfy `DESC`.
|
||||
let nulls = match query.sort {
|
||||
SortField::Author => " NULLS LAST",
|
||||
_ => "",
|
||||
};
|
||||
let order_by = format!("{col} {dir}{nulls}, id");
|
||||
|
||||
let search = query.search.as_deref();
|
||||
let status = query.status.as_deref();
|
||||
|
||||
Reference in New Issue
Block a user