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:
MechaCat02
2026-06-25 07:15:51 +02:00
parent 93b7e451bf
commit dee53fa212
16 changed files with 936 additions and 75 deletions

View File

@@ -81,7 +81,7 @@ Everything is namespaced under `/api/v1/`. `/api/*` outside the version prefix i
| Method | Path | Description | | Method | Path | Description |
| ------ | ------------------------------------------------------- | ------------------------------------------ | | ------ | ------------------------------------------------------- | ------------------------------------------ |
| GET | `/api/v1/health` | Liveness probe. | | GET | `/api/v1/health` | Liveness probe. |
| GET | `/api/v1/mangas?search=&sort=recent|title&limit=&offset=` | List/search mangas. Trigram fuzzy search. | | GET | `/api/v1/mangas?search=&sort=created\|updated\|title\|author&order=asc\|desc&limit=&offset=` | List/search mangas. Trigram fuzzy search. `sort` defaults to `updated`; `order` defaults per field (dates `desc`, text `asc`). `sort=recent` is a back-compat alias for `created`. |
| GET | `/api/v1/mangas/{id}` | Single manga. | | GET | `/api/v1/mangas/{id}` | Single manga. |
| GET | `/api/v1/mangas/{id}/chapters` | Paginated chapter list, ordered by number. | | GET | `/api/v1/mangas/{id}/chapters` | Paginated chapter list, ordered by number. |
| GET | `/api/v1/mangas/{id}/chapters/{n}` | Single chapter. | | GET | `/api/v1/mangas/{id}/chapters/{n}` | Single chapter. |

2
backend/Cargo.lock generated
View File

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

View File

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

View File

@@ -0,0 +1,16 @@
-- Back the default catalog ordering. Since 0.88.0 the catalog list defaults to
-- `ORDER BY updated_at DESC, id` (the no-filter default path), but the only
-- existing updated_at index on mangas is the PARTIAL `mangas_missing_cover_idx`
-- (WHERE cover_image_path IS NULL), which Postgres can't use for the unfiltered
-- ordering. `created_at` and `lower(title)` already have full indexes from
-- 0001; this gives the new default sort column the same treatment.
--
-- `id` is included as a trailing key so the index also covers the stable
-- `, id` tie-break the listing appends for deterministic pagination.
--
-- Not CONCURRENTLY: sqlx::migrate! wraps each migration in a transaction, and
-- CREATE INDEX CONCURRENTLY can't run inside one. The table is small at our
-- scale, so a brief lock on an online deploy is acceptable.
CREATE INDEX IF NOT EXISTS mangas_updated_at_idx
ON mangas (updated_at DESC, id);

View File

@@ -51,14 +51,58 @@ pub struct ListParams {
pub limit: i64, pub limit: i64,
#[serde(default)] #[serde(default)]
pub offset: i64, pub offset: i64,
/// Sort field: `created`, `updated` (default), `title`, or `author`.
/// Also accepts the legacy `recent` alias (== `created`). Anything
/// else → 422.
#[serde(default)] #[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 { fn default_limit() -> i64 {
50 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>> { fn parse_uuid_csv(field: &str, raw: Option<&str>) -> AppResult<Vec<Uuid>> {
let Some(raw) = raw else { return Ok(Vec::new()) }; let Some(raw) = raw else { return Ok(Vec::new()) };
let mut out = Vec::new(); let mut out = Vec::new();
@@ -94,6 +138,10 @@ async fn list(
Some(s.to_string()) 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 { let q = repo::manga::ListQuery {
search: params.search.filter(|s| !s.trim().is_empty()), search: params.search.filter(|s| !s.trim().is_empty()),
status, status,
@@ -104,7 +152,8 @@ async fn list(
cw_exclude: crate::api::page_tags::parse_warnings_csv(params.cw_exclude.as_deref())?, cw_exclude: crate::api::page_tags::parse_warnings_csv(params.cw_exclude.as_deref())?,
limit, limit,
offset, offset,
sort: params.sort, sort,
order,
}; };
let (items, total) = repo::manga::list_cards(&state.db, &q).await?; let (items, total) = repo::manga::list_cards(&state.db, &q).await?;
Ok(Json(PagedResponse::with_total(items, limit, offset, total))) Ok(Json(PagedResponse::with_total(items, limit, offset, total)))

View File

@@ -5,7 +5,6 @@
//! handlers depend only on `sqlx::PgPool`, not on a trait object. Swap to //! handlers depend only on `sqlx::PgPool`, not on a trait object. Swap to
//! a trait + impl if a second backend ever becomes necessary. //! a trait + impl if a second backend ever becomes necessary.
use serde::Deserialize;
use sqlx::{PgConnection, PgExecutor, PgPool}; use sqlx::{PgConnection, PgExecutor, PgPool};
use uuid::Uuid; use uuid::Uuid;
@@ -18,14 +17,43 @@ use crate::repo;
pub const STATUSES: &[&str] = &["ongoing", "completed"]; pub const STATUSES: &[&str] = &["ongoing", "completed"];
pub const DEFAULT_STATUS: &str = "ongoing"; pub const DEFAULT_STATUS: &str = "ongoing";
#[derive(Debug, Clone, Copy, Default, Deserialize)] /// Which column the listing is ordered by. The direction lives in a separate
#[serde(rename_all = "snake_case")] /// [`SortOrder`] so any field can be sorted either way. Wire values are parsed
pub enum ListSort { /// (with validation and the legacy `recent` alias) in `api::mangas`, not via
/// Newest first (default). /// 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] #[default]
Recent, Updated,
/// A→Z by title (case-insensitive). /// Title (case-insensitive).
Title, 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)] #[derive(Debug, Clone, Default)]
@@ -42,7 +70,8 @@ pub struct ListQuery {
pub cw_exclude: Vec<String>, pub cw_exclude: Vec<String>,
pub limit: i64, pub limit: i64,
pub offset: 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`], /// 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 /// Returns the page of mangas matching `query` plus the unfiltered total
/// count for the same filter. The trigram GIN indexes (see 0005_search.sql /// count for the same filter. The date/title sort columns are index-backed
/// and 0009_manga_metadata.sql) keep both queries cheap as the library /// (`mangas_created_at_idx`, `mangas_updated_at_idx`, `mangas_title_lower_idx`)
/// grows. /// 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)> { pub async fn list(pool: &PgPool, query: &ListQuery) -> AppResult<(Vec<Manga>, i64)> {
// `order_by` is interpolated from a hard-coded enum, never from request // Both `col` and `dir` are interpolated from hard-coded enums, never from
// input, so this is not a SQL injection seam. // request input, so this is not a SQL injection seam. The trailing `id` is
let order_by = match query.sort { // a stable tie-break that keeps pagination deterministic across rows with
ListSort::Recent => "created_at DESC, id", // equal sort keys.
ListSort::Title => "lower(title) ASC, id", 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 search = query.search.as_deref();
let status = query.status.as_deref(); let status = query.status.as_deref();

View File

@@ -11,6 +11,53 @@ fn metadata(title: &str) -> serde_json::Value {
json!({ "title": title }) 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")] #[sqlx::test(migrations = "./migrations")]
async fn list_is_empty_initially(pool: PgPool) { async fn list_is_empty_initially(pool: PgPool) {
let h = common::harness(pool); let h = common::harness(pool);
@@ -103,19 +150,307 @@ async fn list_sort_title_orders_alphabetically(pool: PgPool) {
.unwrap(); .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&order=asc"))
.await
.unwrap();
let body = common::body_json(resp).await;
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 list_sort_recent_alias_maps_to_created_desc(pool: PgPool) {
// `recent` was the pre-0.88 sort value (newest created first). It is kept
// as an alias for `created` so existing bots/scripts don't break.
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;
let resp = h
.app
.oneshot(common::get("/api/v1/mangas?sort=recent"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = common::body_json(resp).await;
// Same ordering as `sort=created&order=desc`: newest-created first.
assert_eq!(title_list(&body), vec!["Bravo", "Charlie", "Alpha"]);
}
#[sqlx::test(migrations = "./migrations")]
async fn list_sort_field_defaults_direction_per_field(pool: PgPool) {
// When `order` is omitted, the API applies the field's natural direction:
// text fields ascend (A→Z), matching the frontend's `defaultOrderFor`, so
// a bare `?sort=title` link reads the same in the UI and over the wire.
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 let resp = h
.app .app
.oneshot(common::get("/api/v1/mangas?sort=title")) .oneshot(common::get("/api/v1/mangas?sort=title"))
.await .await
.unwrap(); .unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = common::body_json(resp).await; let body = common::body_json(resp).await;
let titles: Vec<&str> = body["items"] assert_eq!(title_list(&body), vec!["Berserk", "One Piece", "Vinland Saga"]);
.as_array() }
.unwrap()
#[sqlx::test(migrations = "./migrations")]
async fn list_sort_author_default_is_ascending_nulls_last(pool: PgPool) {
// The other text field: a bare `?sort=author` must default to ascending and
// keep authorless mangas last (NULLS LAST), exercising the omitted-order
// path through the author subquery — not just `title`.
let h = common::harness(pool);
let (_, cookie) = common::register_user(&h.app).await;
for (title, authors) in [
("Akira", json!(["Beta Author"])),
("Boku", json!(["Alpha 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();
}
let resp = h
.app
.oneshot(common::get("/api/v1/mangas?sort=author"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = common::body_json(resp).await;
// Alpha Author (Boku) < Beta Author (Akira); authorless sorts last.
assert_eq!(title_list(&body), vec!["Boku", "Akira", "NoAuthor"]);
}
#[sqlx::test(migrations = "./migrations")]
async fn list_rejects_invalid_sort_and_order_with_envelope(pool: PgPool) {
let h = common::harness(pool);
// Unknown sort field → structured 422, not axum's plain-text 400.
let resp = h
.app
.clone()
.oneshot(common::get("/api/v1/mangas?sort=bogus"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
let body = common::body_json(resp).await;
assert_eq!(body["error"]["details"]["sort"], "invalid");
// Unknown order → same treatment.
let resp = h
.app
.oneshot(common::get("/api/v1/mangas?order=sideways"))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
let body = common::body_json(resp).await;
assert_eq!(body["error"]["details"]["order"], "invalid");
}
/// Pin a manga's primary key to an explicit UUID. Safe only for freshly
/// seeded mangas with no chapters/authors/tags referencing them.
async fn set_id(pool: &PgPool, title: &str, id: &str) {
let uuid: uuid::Uuid = id.parse().unwrap();
sqlx::query("UPDATE mangas SET id = $1 WHERE title = $2")
.bind(uuid)
.bind(title)
.execute(pool)
.await
.unwrap();
}
#[sqlx::test(migrations = "./migrations")]
async fn list_tie_break_orders_equal_keys_by_ascending_id(pool: PgPool) {
// The trailing `, id` in ORDER BY is what keeps pagination stable when the
// primary sort key ties. Pin three mangas to the SAME created_at and assign
// ids whose ascending order (Bravo < Charlie < Alpha) deliberately differs
// from insertion/physical order, so the expected ordering can ONLY come
// from the id tie-break.
//
// We sort by `created` on purpose: `mangas_created_at_idx` is `(created_at
// DESC)` with no id, so it does NOT encode the secondary order — unlike the
// default `updated` path, whose `mangas_updated_at_idx (updated_at DESC,
// id)` would mask a missing clause. Drop `, id` from the query and this
// test fails.
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, title, "2022-01-01T00:00:00Z").await;
}
set_id(&pool, "Alpha", "33333333-3333-4333-8333-333333333333").await;
set_id(&pool, "Bravo", "11111111-1111-4111-8111-111111111111").await;
set_id(&pool, "Charlie", "22222222-2222-4222-8222-222222222222").await;
let page = |limit: i64, offset: i64| {
let app = h.app.clone();
async move {
let resp = app
.oneshot(common::get(&format!(
"/api/v1/mangas?sort=created&limit={limit}&offset={offset}"
)))
.await
.unwrap();
common::body_json(resp).await
}
};
// Single page: tied rows come back in ascending-id order.
let full = page(50, 0).await;
assert_eq!(title_list(&full), vec!["Bravo", "Charlie", "Alpha"]);
// Paginating one row at a time reproduces that exact sequence — no overlap,
// no gap — which only holds because the id tie-break makes the order total.
let paged: Vec<String> = vec![page(1, 0).await, page(1, 1).await, page(1, 2).await]
.iter() .iter()
.map(|m| m["title"].as_str().unwrap()) .map(|b| b["items"][0]["title"].as_str().unwrap().to_string())
.collect(); .collect();
assert_eq!(titles, vec!["Berserk", "One Piece", "Vinland Saga"]); assert_eq!(paged, vec!["Bravo", "Charlie", "Alpha"]);
} }
#[sqlx::test(migrations = "./migrations")] #[sqlx::test(migrations = "./migrations")]

View File

@@ -149,14 +149,16 @@ test.describe('mobile catalog chrome', () => {
await expect(page).toHaveURL((url) => !url.search.includes('genres=')); await expect(page).toHaveURL((url) => !url.search.includes('genres='));
}); });
test('phone viewport: Sort sheet swaps the sort and dismisses on pick', async ({ test('phone viewport: Sort sheet swaps field + direction, staying open', async ({
page page
}) => { }) => {
let lastSortParam: string | null = null; let lastSortParam: string | null = null;
let lastOrderParam: string | null = null;
await mockAnonymous(page); await mockAnonymous(page);
await mockCatalog(page, { await mockCatalog(page, {
capture: (url) => { capture: (url) => {
lastSortParam = url.searchParams.get('sort'); lastSortParam = url.searchParams.get('sort');
lastOrderParam = url.searchParams.get('order');
} }
}); });
await page.setViewportSize(MOBILE); await page.setViewportSize(MOBILE);
@@ -166,13 +168,27 @@ test.describe('mobile catalog chrome', () => {
await page.getByTestId('sort-chip').click(); await page.getByTestId('sort-chip').click();
await expect(page.getByTestId('sort-sheet')).toBeVisible(); await expect(page.getByTestId('sort-sheet')).toBeVisible();
// Use click(), not check(): the onchange handler closes the sheet // Picking a field reloads but keeps the sheet open so the direction
// synchronously so the radio is gone before check() can verify the // can be adjusted in the same interaction.
// `checked` state. await page.getByTestId('sort-sheet').getByRole('radio', { name: /^Title$/ }).click();
await page.getByTestId('sort-sheet').getByRole('radio', { name: /Title/ }).click(); await expect(page.getByTestId('sort-sheet')).toBeVisible();
await expect(page.getByTestId('sort-sheet')).toBeHidden();
await expect(page).toHaveURL(/sort=title/); await expect(page).toHaveURL(/sort=title/);
expect(lastSortParam).toBe('title'); expect(lastSortParam).toBe('title');
// The API call always carries an explicit direction; Title's natural
// default is A→Z (asc)...
expect(lastOrderParam).toBe('asc');
// ...but the browser URL omits it since it's the default.
await expect(page).not.toHaveURL(/order=/);
// Flipping the direction to Z→A surfaces an explicit order param both
// on the wire and in the URL.
await page.getByTestId('sort-order-mobile-desc').click();
await expect(page).toHaveURL(/order=desc/);
expect(lastOrderParam).toBe('desc');
// The Done button gives an explicit dismissal affordance once the
// field + direction are set.
await page.getByTestId('sort-done').click();
await expect(page.getByTestId('sort-sheet')).toBeHidden();
}); });
}); });

View File

@@ -1,6 +1,6 @@
{ {
"name": "mangalord-frontend", "name": "mangalord-frontend",
"version": "0.87.26", "version": "0.88.0",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {

View File

@@ -89,7 +89,7 @@ describe('mangas api client', () => {
expect(result.page).toEqual({ limit: 50, offset: 0, total: 1 }); expect(result.page).toEqual({ limit: 50, offset: 0, total: 1 });
}); });
it('listMangas encodes search, status, ids (csv), limit, offset, sort', async () => { it('listMangas encodes search, status, ids (csv), limit, offset, sort, order', async () => {
fetchSpy.mockResolvedValueOnce(ok(emptyPage())); fetchSpy.mockResolvedValueOnce(ok(emptyPage()));
await listMangas({ await listMangas({
search: 'one piece', search: 'one piece',
@@ -99,7 +99,8 @@ describe('mangas api client', () => {
tagIds: ['t1', 't2'], tagIds: ['t1', 't2'],
limit: 10, limit: 10,
offset: 20, offset: 20,
sort: 'title' sort: 'title',
order: 'asc'
}); });
const url = fetchSpy.mock.calls[0][0] as string; const url = fetchSpy.mock.calls[0][0] as string;
expect(url).toMatch(/\/v1\/mangas\?/); expect(url).toMatch(/\/v1\/mangas\?/);
@@ -113,6 +114,7 @@ describe('mangas api client', () => {
expect(url).toContain('limit=10'); expect(url).toContain('limit=10');
expect(url).toContain('offset=20'); expect(url).toContain('offset=20');
expect(url).toContain('sort=title'); expect(url).toContain('sort=title');
expect(url).toContain('order=asc');
}); });
it('getManga returns the enriched detail shape', async () => { it('getManga returns the enriched detail shape', async () => {

View File

@@ -1,7 +1,8 @@
import { request, type Manga, type MangaStatus, type Page } from './client'; import { request, type Manga, type MangaStatus, type Page } from './client';
import type { ContentWarning } from './page_tags'; import type { ContentWarning } from './page_tags';
export type MangaSort = 'recent' | 'title'; export type MangaSort = 'created' | 'updated' | 'title' | 'author';
export type SortOrder = 'asc' | 'desc';
export type AuthorRef = { id: string; name: string }; export type AuthorRef = { id: string; name: string };
export type GenreRef = { id: string; name: string }; export type GenreRef = { id: string; name: string };
@@ -39,6 +40,7 @@ export type ListOptions = {
limit?: number; limit?: number;
offset?: number; offset?: number;
sort?: MangaSort; sort?: MangaSort;
order?: SortOrder;
}; };
export type MangasPage = { export type MangasPage = {
@@ -68,6 +70,7 @@ export async function listMangas(opts: ListOptions = {}): Promise<MangasPage> {
if (opts.limit != null) params.set('limit', String(opts.limit)); if (opts.limit != null) params.set('limit', String(opts.limit));
if (opts.offset != null) params.set('offset', String(opts.offset)); if (opts.offset != null) params.set('offset', String(opts.offset));
if (opts.sort) params.set('sort', opts.sort); if (opts.sort) params.set('sort', opts.sort);
if (opts.order) params.set('order', opts.order);
const qs = params.toString(); const qs = params.toString();
return request<MangasPage>(`/v1/mangas${qs ? `?${qs}` : ''}`); return request<MangasPage>(`/v1/mangas${qs ? `?${qs}` : ''}`);
} }

View File

@@ -17,14 +17,69 @@
ariaLabel: string; ariaLabel: string;
testid?: string; testid?: string;
} = $props(); } = $props();
// Roving-tabindex refs so arrow keys can move focus across the group.
let buttons = $state<HTMLButtonElement[]>([]);
function select(index: number) {
const opt = options[index];
if (!opt) return;
if (opt.value !== value) onchange(opt.value);
// Selection follows focus, per the WAI-ARIA radiogroup pattern.
buttons[index]?.focus();
}
// ArrowLeft/Up and ArrowRight/Down move (and wrap) through the options;
// Home/End jump to the ends. Without this a control announced as a
// `radiogroup` would not respond to the keys AT users expect.
function onkeydown(event: KeyboardEvent) {
// Navigate relative to the focused button, not the selected `value`:
// this control is parent-controlled, so `value` only updates after a
// re-render — anchoring on focus keeps rapid keypresses from sticking.
// Falls back to `value` when focus is elsewhere (e.g. event delegated
// from outside a child, as in unit tests).
const focused = buttons.findIndex((b) => b === document.activeElement);
const current = focused >= 0 ? focused : options.findIndex((o) => o.value === value);
switch (event.key) {
case 'ArrowRight':
case 'ArrowDown':
event.preventDefault();
select((current + 1) % options.length);
break;
case 'ArrowLeft':
case 'ArrowUp':
event.preventDefault();
select((current - 1 + options.length) % options.length);
break;
case 'Home':
event.preventDefault();
select(0);
break;
case 'End':
event.preventDefault();
select(options.length - 1);
break;
}
}
</script> </script>
<div class="segmented" role="radiogroup" aria-label={ariaLabel} data-testid={testid}> <!-- Keydown is delegated here; focus lives on the child radios via roving
{#each options as opt (opt.value)} tabindex, so the group itself is intentionally not a focus target. -->
<!-- svelte-ignore a11y_interactive_supports_focus -->
<div
class="segmented"
role="radiogroup"
aria-label={ariaLabel}
data-testid={testid}
{onkeydown}
>
{#each options as opt, i (opt.value)}
<button <button
bind:this={buttons[i]}
type="button" type="button"
role="radio" role="radio"
aria-checked={opt.value === value} aria-checked={opt.value === value}
tabindex={opt.value === value ? 0 : -1}
class="seg" class="seg"
class:active={opt.value === value} class:active={opt.value === value}
onclick={() => { onclick={() => {

View File

@@ -1,5 +1,5 @@
import { describe, it, expect, vi, afterEach } from 'vitest'; import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/svelte'; import { render, screen, cleanup, fireEvent } from '@testing-library/svelte';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
afterEach(() => cleanup()); afterEach(() => cleanup());
@@ -50,4 +50,74 @@ describe('SegmentedControl', () => {
}); });
expect(screen.getByRole('radiogroup', { name: 'Library tab' })).toBeTruthy(); expect(screen.getByRole('radiogroup', { name: 'Library tab' })).toBeTruthy();
}); });
it('gives the selected option a roving tabindex of 0 and the rest -1', () => {
render(SegmentedControl, {
props: { options: opts, value: 'collections', onchange: () => {}, ariaLabel: 'Library tab' }
});
expect(screen.getByRole('radio', { name: 'Collections' }).getAttribute('tabindex')).toBe('0');
expect(screen.getByRole('radio', { name: 'Bookmarks' }).getAttribute('tabindex')).toBe('-1');
expect(screen.getByRole('radio', { name: 'History' }).getAttribute('tabindex')).toBe('-1');
});
it('selects the next option on ArrowRight/ArrowDown (selection follows focus)', async () => {
const onchange = vi.fn();
render(SegmentedControl, {
props: { options: opts, value: 'bookmarks', onchange, ariaLabel: 'Library tab' }
});
const group = screen.getByRole('radiogroup', { name: 'Library tab' });
const first = screen.getByRole('radio', { name: 'Bookmarks' });
first.focus();
await fireEvent.keyDown(group, { key: 'ArrowRight' });
expect(onchange).toHaveBeenCalledWith('collections');
onchange.mockClear();
// Re-anchor on the first option to assert ArrowDown behaves the same.
first.focus();
await fireEvent.keyDown(group, { key: 'ArrowDown' });
expect(onchange).toHaveBeenCalledWith('collections');
});
it('wraps from the first option to the last on ArrowLeft', async () => {
const onchange = vi.fn();
render(SegmentedControl, {
props: { options: opts, value: 'bookmarks', onchange, ariaLabel: 'Library tab' }
});
await fireEvent.keyDown(screen.getByRole('radiogroup', { name: 'Library tab' }), {
key: 'ArrowLeft'
});
expect(onchange).toHaveBeenCalledWith('history');
});
it('jumps to the first/last option with Home/End', async () => {
const onchange = vi.fn();
render(SegmentedControl, {
props: { options: opts, value: 'collections', onchange, ariaLabel: 'Library tab' }
});
const group = screen.getByRole('radiogroup', { name: 'Library tab' });
await fireEvent.keyDown(group, { key: 'Home' });
expect(onchange).toHaveBeenCalledWith('bookmarks');
onchange.mockClear();
await fireEvent.keyDown(group, { key: 'End' });
expect(onchange).toHaveBeenCalledWith('history');
});
// Navigation anchors on the focused button, not the (parent-controlled,
// lagging) `value` prop: even when `value` never updates, consecutive
// ArrowRights fired on the focused child advance step by step. This pins
// both the keydown-bubbles-from-child path and the no-stick behavior.
it('advances step by step on consecutive ArrowRights, following focus', async () => {
const onchange = vi.fn();
render(SegmentedControl, {
props: { options: opts, value: 'bookmarks', onchange, ariaLabel: 'Library tab' }
});
screen.getByRole('radio', { name: 'Bookmarks' }).focus();
await fireEvent.keyDown(document.activeElement as Element, { key: 'ArrowRight' });
expect(onchange).toHaveBeenLastCalledWith('collections');
expect((document.activeElement as HTMLElement).textContent?.trim()).toBe('Collections');
// `value` is still 'bookmarks' (vi.fn never feeds it back), yet the next
// press lands on the third option because it anchors on focus.
await fireEvent.keyDown(document.activeElement as Element, { key: 'ArrowRight' });
expect(onchange).toHaveBeenLastCalledWith('history');
expect((document.activeElement as HTMLElement).textContent?.trim()).toBe('History');
});
}); });

View File

@@ -0,0 +1,91 @@
import { describe, it, expect } from 'vitest';
import type { MangaSort, SortOrder } from './api/mangas';
import {
DEFAULT_SORT,
defaultOrderFor,
isTextField,
dirOptions,
dirLabel,
sortLabel,
coerceSort,
coerceOrder,
sortUrlParams
} from './mangaSort';
const FIELDS: MangaSort[] = ['created', 'updated', 'title', 'author'];
const ORDERS: SortOrder[] = ['asc', 'desc'];
describe('mangaSort', () => {
it('classifies text vs date fields', () => {
expect(isTextField('title')).toBe(true);
expect(isTextField('author')).toBe(true);
expect(isTextField('created')).toBe(false);
expect(isTextField('updated')).toBe(false);
});
it('defaults date fields to desc and text fields to asc', () => {
expect(defaultOrderFor('created')).toBe('desc');
expect(defaultOrderFor('updated')).toBe('desc');
expect(defaultOrderFor('title')).toBe('asc');
expect(defaultOrderFor('author')).toBe('asc');
});
it('labels the direction toggle per field type', () => {
expect(dirOptions('title').map((o) => o.label)).toEqual(['A→Z', 'Z→A']);
expect(dirOptions('updated').map((o) => o.label)).toEqual(['Newest', 'Oldest']);
});
it('dirLabel never returns empty for a valid order', () => {
for (const f of FIELDS) {
for (const o of ORDERS) {
expect(dirLabel(f, o)).not.toBe('');
}
}
});
it('composes a readable sort label without a dangling separator', () => {
expect(sortLabel('updated', 'desc')).toBe('Last updated · Newest');
expect(sortLabel('title', 'asc')).toBe('Title · A→Z');
expect(sortLabel('author', 'desc')).toBe('Author · Z→A');
});
it('coerceSort accepts valid fields and falls back to the default otherwise', () => {
for (const f of FIELDS) expect(coerceSort(f)).toBe(f);
expect(coerceSort('bogus')).toBe(DEFAULT_SORT);
expect(coerceSort(null)).toBe(DEFAULT_SORT);
});
it('coerceSort honors the legacy `recent` alias (== created), matching the API', () => {
// The backend maps sort=recent -> created; the browser must agree so a
// pasted/legacy `/?sort=recent` URL resolves to the same field.
expect(coerceSort('recent')).toBe('created');
});
it('coerceOrder accepts asc/desc and otherwise uses the field default', () => {
expect(coerceOrder('asc', 'title')).toBe('asc');
expect(coerceOrder('desc', 'title')).toBe('desc');
// Absent/invalid → field's natural default.
expect(coerceOrder(null, 'title')).toBe('asc');
expect(coerceOrder('sideways', 'updated')).toBe('desc');
});
it('omits sort/order from the URL when they equal the defaults', () => {
expect(sortUrlParams('updated', 'desc')).toEqual({});
// Title at its natural default (asc) → only the field is persisted.
expect(sortUrlParams('title', 'asc')).toEqual({ sort: 'title' });
// Non-default direction is persisted explicitly.
expect(sortUrlParams('title', 'desc')).toEqual({ sort: 'title', order: 'desc' });
expect(sortUrlParams('updated', 'asc')).toEqual({ order: 'asc' });
});
it('round-trips every field/order combo losslessly through the URL', () => {
for (const sort of FIELDS) {
for (const order of ORDERS) {
const params = sortUrlParams(sort, order);
const back = coerceSort(params.sort ?? null);
const backOrder = coerceOrder(params.order ?? null, back);
expect({ sort: back, order: backOrder }).toEqual({ sort, order });
}
}
});
});

View File

@@ -0,0 +1,83 @@
import type { MangaSort, SortOrder } from './api/mangas';
/// The catalog's default sort field. A bare `/?` (no `sort`) means this.
export const DEFAULT_SORT: MangaSort = 'updated';
export const SORT_FIELD_LABELS: Record<MangaSort, string> = {
updated: 'Last updated',
created: 'Date added',
title: 'Title',
author: 'Author'
};
/** Text fields sort A→Z by default; date fields newest-first. */
export function isTextField(f: MangaSort): boolean {
return f === 'title' || f === 'author';
}
/**
* The direction applied when `order` is omitted. This mirrors the backend's
* `SortField::default_order` (backend/src/repo/manga.rs) on purpose: a bare
* `?sort=<field>` link must read the same in the UI and over the wire.
*/
export function defaultOrderFor(f: MangaSort): SortOrder {
return isTextField(f) ? 'asc' : 'desc';
}
/** The asc/desc toggle options, labelled for the field type. */
export function dirOptions(f: MangaSort): { label: string; value: SortOrder }[] {
return isTextField(f)
? [
{ label: 'A→Z', value: 'asc' },
{ label: 'Z→A', value: 'desc' }
]
: [
{ label: 'Newest', value: 'desc' },
{ label: 'Oldest', value: 'asc' }
];
}
export function dirLabel(sort: MangaSort, order: SortOrder): string {
return dirOptions(sort).find((o) => o.value === order)?.label ?? '';
}
export function sortLabel(sort: MangaSort, order: SortOrder): string {
return `${SORT_FIELD_LABELS[sort]} · ${dirLabel(sort, order)}`;
}
/**
* Coerce a raw `sort` query value to a valid field, falling back to default.
* `recent` is honored as the same back-compat alias the API exposes (== the
* `created` field), so a hand-shared or legacy `/?sort=recent` URL resolves to
* the same field in the browser as over the wire.
*/
export function coerceSort(raw: string | null | undefined): MangaSort {
if (raw === 'recent') return 'created';
return raw === 'created' || raw === 'updated' || raw === 'title' || raw === 'author'
? raw
: DEFAULT_SORT;
}
/**
* Coerce a raw `order` query value, falling back to the field's natural
* default when absent or invalid — mirroring how {@link sortUrlParams} omits it.
*/
export function coerceOrder(raw: string | null | undefined, sort: MangaSort): SortOrder {
return raw === 'asc' || raw === 'desc' ? raw : defaultOrderFor(sort);
}
/**
* The `sort`/`order` params to persist in the shareable URL. Defaults are
* omitted to keep the common URL clean; because the backend resolves an absent
* `order` to {@link defaultOrderFor} too, the omission is unambiguous across
* the UI and direct API callers.
*/
export function sortUrlParams(
sort: MangaSort,
order: SortOrder
): { sort?: MangaSort; order?: SortOrder } {
const out: { sort?: MangaSort; order?: SortOrder } = {};
if (sort !== DEFAULT_SORT) out.sort = sort;
if (order !== defaultOrderFor(sort)) out.order = order;
return out;
}

View File

@@ -7,13 +7,25 @@
listMangas, listMangas,
type MangaCard as MangaCardData, type MangaCard as MangaCardData,
type MangaSort, type MangaSort,
type SortOrder,
type MangaStatus type MangaStatus
} from '$lib/api/mangas'; } from '$lib/api/mangas';
import { listGenres, type Genre } from '$lib/api/genres'; import { listGenres, type Genre } from '$lib/api/genres';
import { listTags, type Tag } from '$lib/api/tags'; import { listTags, type Tag } from '$lib/api/tags';
import {
DEFAULT_SORT,
SORT_FIELD_LABELS,
defaultOrderFor,
dirOptions as dirOptionsFor,
coerceSort,
coerceOrder,
sortLabel as composeSortLabel,
sortUrlParams
} from '$lib/mangaSort';
import Chip from '$lib/components/Chip.svelte'; import Chip from '$lib/components/Chip.svelte';
import MangaCard from '$lib/components/MangaCard.svelte'; import MangaCard from '$lib/components/MangaCard.svelte';
import Pager from '$lib/components/Pager.svelte'; import Pager from '$lib/components/Pager.svelte';
import SegmentedControl from '$lib/components/SegmentedControl.svelte';
import Sheet from '$lib/components/Sheet.svelte'; import Sheet from '$lib/components/Sheet.svelte';
import Search from '@lucide/svelte/icons/search'; import Search from '@lucide/svelte/icons/search';
import SlidersHorizontal from '@lucide/svelte/icons/sliders-horizontal'; import SlidersHorizontal from '@lucide/svelte/icons/sliders-horizontal';
@@ -25,7 +37,8 @@
let mangas: MangaCardData[] = $state([]); let mangas: MangaCardData[] = $state([]);
let search = $state(''); let search = $state('');
let sort = $state<MangaSort>('recent'); let sort = $state<MangaSort>(DEFAULT_SORT);
let order = $state<SortOrder>(defaultOrderFor(DEFAULT_SORT));
let statusFilter = $state<'' | MangaStatus>(''); let statusFilter = $state<'' | MangaStatus>('');
let selectedGenres = $state<Genre[]>([]); let selectedGenres = $state<Genre[]>([]);
let selectedTags = $state<Tag[]>([]); let selectedTags = $state<Tag[]>([]);
@@ -55,7 +68,12 @@
(statusFilter ? 1 : 0) + selectedGenres.length + selectedTags.length (statusFilter ? 1 : 0) + selectedGenres.length + selectedTags.length
); );
const sortLabel = $derived(sort === 'title' ? 'Title (A→Z)' : 'Recent'); // Field/direction labelling and defaults live in $lib/mangaSort (unit
// tested there). Date fields read newest-first; text fields A→Z. The
// direction stays freely togglable — defaultOrderFor only picks the
// direction applied when the field changes.
const dirOptions = $derived(dirOptionsFor(sort));
const sortLabel = $derived(composeSortLabel(sort, order));
const totalPages = $derived( const totalPages = $derived(
total != null && total > 0 ? Math.ceil(total / PAGE_SIZE) : 1 total != null && total > 0 ? Math.ceil(total / PAGE_SIZE) : 1
@@ -76,6 +94,7 @@
genreIds: selectedGenres.map((g) => g.id), genreIds: selectedGenres.map((g) => g.id),
tagIds: selectedTags.map((t) => t.id), tagIds: selectedTags.map((t) => t.id),
sort, sort,
order,
limit: PAGE_SIZE, limit: PAGE_SIZE,
offset: (currentPage - 1) * PAGE_SIZE offset: (currentPage - 1) * PAGE_SIZE
}); });
@@ -92,7 +111,11 @@
if (!browser) return; if (!browser) return;
const params = new URLSearchParams(); const params = new URLSearchParams();
if (search.trim()) params.set('q', search.trim()); if (search.trim()) params.set('q', search.trim());
if (sort !== 'recent') params.set('sort', sort); // Defaults are omitted to keep the URL clean; the backend resolves an
// absent `sort`/`order` the same way, so the omission is unambiguous.
const sp = sortUrlParams(sort, order);
if (sp.sort) params.set('sort', sp.sort);
if (sp.order) params.set('order', sp.order);
if (statusFilter) params.set('status', statusFilter); if (statusFilter) params.set('status', statusFilter);
if (selectedGenres.length) if (selectedGenres.length)
params.set('genres', selectedGenres.map((g) => g.id).join(',')); params.set('genres', selectedGenres.map((g) => g.id).join(','));
@@ -126,8 +149,10 @@
// Genre objects so the chip rows render real labels. // Genre objects so the chip rows render real labels.
const url = new URL($page.url); const url = new URL($page.url);
search = url.searchParams.get('q') ?? ''; search = url.searchParams.get('q') ?? '';
const s = url.searchParams.get('sort'); sort = coerceSort(url.searchParams.get('sort'));
if (s === 'title' || s === 'recent') sort = s; // Fall back to the field's natural default when `order` is absent or
// invalid, mirroring how syncUrl omits the default.
order = coerceOrder(url.searchParams.get('order'), sort);
const st = url.searchParams.get('status'); const st = url.searchParams.get('status');
statusFilter = st === 'ongoing' || st === 'completed' ? st : ''; statusFilter = st === 'ongoing' || st === 'completed' ? st : '';
const genreIds = (url.searchParams.get('genres') ?? '') const genreIds = (url.searchParams.get('genres') ?? '')
@@ -166,6 +191,15 @@
} }
function onSortChange() { function onSortChange() {
// Changing the field snaps the direction back to that field's natural
// default (dates → Newest, text → A→Z); the user can flip afterwards.
order = defaultOrderFor(sort);
resetAndReload();
}
function pickOrder(next: SortOrder) {
if (next === order) return;
order = next;
resetAndReload(); resetAndReload();
} }
@@ -249,12 +283,12 @@
} }
function pickSort(next: MangaSort) { function pickSort(next: MangaSort) {
if (next === sort) { if (next === sort) return;
sortSheetOpen = false;
return;
}
sort = next; sort = next;
sortSheetOpen = false; // Match desktop: snap to the field's natural direction. The sheet
// stays open so the user can also adjust the direction before
// dismissing it.
order = defaultOrderFor(sort);
resetAndReload(); resetAndReload();
} }
@@ -504,10 +538,22 @@
<label class="sort"> <label class="sort">
<span>Sort</span> <span>Sort</span>
<select bind:value={sort} onchange={onSortChange} data-testid="sort-select"> <select bind:value={sort} onchange={onSortChange} data-testid="sort-select">
<option value="recent">Recent</option> <option value="updated">Last updated</option>
<option value="title">Title (A→Z)</option> <option value="created">Date added</option>
<option value="title">Title</option>
<option value="author">Author</option>
</select> </select>
</label> </label>
<div class="sort">
<span>Direction</span>
<SegmentedControl
options={dirOptions}
value={order}
onchange={pickOrder}
ariaLabel="Sort direction"
testid="sort-order"
/>
</div>
</div> </div>
</form> </form>
@@ -526,30 +572,44 @@
onClose={() => (sortSheetOpen = false)} onClose={() => (sortSheetOpen = false)}
testid="sort-sheet" testid="sort-sheet"
> >
<div class="sort-options"> <p id="sort-field-heading" class="sort-section-label">Sort by</p>
<label> <div class="sort-options" role="radiogroup" aria-labelledby="sort-field-heading">
<input {#each Object.entries(SORT_FIELD_LABELS) as [value, label] (value)}
type="radio" <label>
name="sort-mobile" <input
value="recent" type="radio"
aria-label="Recent" name="sort-mobile"
checked={sort === 'recent'} {value}
onchange={() => pickSort('recent')} aria-label={label}
/> checked={sort === value}
<span>Recent</span> onchange={() => pickSort(value as MangaSort)}
</label> />
<label> <!-- aria-label duplicates the visible span text on purpose so
<input the e2e getByRole('radio', { name }) lookup is stable. -->
type="radio" <span>{label}</span>
name="sort-mobile" </label>
value="title" {/each}
aria-label="Title (A→Z)"
checked={sort === 'title'}
onchange={() => pickSort('title')}
/>
<span>Title (A→Z)</span>
</label>
</div> </div>
<div class="sort-direction">
<p class="sort-section-label">Direction</p>
<SegmentedControl
options={dirOptions}
value={order}
onchange={pickOrder}
ariaLabel="Sort direction"
testid="sort-order-mobile"
/>
</div>
{#snippet footer()}
<button
type="button"
class="primary"
onclick={() => (sortSheetOpen = false)}
data-testid="sort-done"
>
Done
</button>
{/snippet}
</Sheet> </Sheet>
{#if loading} {#if loading}
@@ -836,6 +896,32 @@
cursor: pointer; cursor: pointer;
} }
.sort-direction {
margin-top: var(--space-3);
padding-top: var(--space-3);
border-top: 1px solid var(--border);
}
/* Section headings inside the mobile sort sheet ("Sort by" / "Direction")
so each group is visibly labelled, mirroring the desktop inline labels. */
.sort-section-label {
margin: 0 0 var(--space-2);
font-size: var(--font-sm);
font-weight: var(--weight-medium);
color: var(--text-muted);
}
.primary {
border: 1px solid var(--primary);
background: var(--primary);
color: var(--primary-contrast);
}
.primary:hover {
background: var(--primary-hover);
border-color: var(--primary-hover);
}
.icon-btn { .icon-btn {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;