fix(mangas): address review on sort feature — alias, index, validation, a11y

Backend
- sort=recent stays a back-compat alias for created (parse_sort); invalid
  sort/order now return the structured 422 envelope instead of plain-text 400
- per-field default direction on omitted order (dates desc, text asc), matching
  the frontend so a bare ?sort=<field> reads the same in UI and API
- migration 0033: index mangas(updated_at DESC, id) backing the default sort
  and its id tie-break; NULLS LAST now applied only to the nullable author key
- tests: recent alias, per-field default (title+author), invalid-value 422,
  and a tie-break test that pins ordering by ascending id (mutation-verified)

Frontend
- pure sort helpers extracted to $lib/mangaSort with unit tests; coerceSort
  honors the recent alias so pasted/legacy URLs resolve to the same field
- SegmentedControl: roving tabindex + arrow/Home/End keyboard nav, anchored on
  focus so rapid keypresses don't stick
- UX: visible "Direction" labels (desktop + mobile), mobile sort-sheet section
  headings and a "Done" button; README sort/order contract updated

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-06-25 07:15:33 +02:00
parent 1079a0151a
commit 78edea4277
11 changed files with 650 additions and 73 deletions

View File

@@ -12,6 +12,16 @@
} from '$lib/api/mangas';
import { listGenres, type Genre } from '$lib/api/genres';
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 MangaCard from '$lib/components/MangaCard.svelte';
import Pager from '$lib/components/Pager.svelte';
@@ -27,8 +37,8 @@
let mangas: MangaCardData[] = $state([]);
let search = $state('');
let sort = $state<MangaSort>('updated');
let order = $state<SortOrder>('desc');
let sort = $state<MangaSort>(DEFAULT_SORT);
let order = $state<SortOrder>(defaultOrderFor(DEFAULT_SORT));
let statusFilter = $state<'' | MangaStatus>('');
let selectedGenres = $state<Genre[]>([]);
let selectedTags = $state<Tag[]>([]);
@@ -58,37 +68,12 @@
(statusFilter ? 1 : 0) + selectedGenres.length + selectedTags.length
);
// Date fields read most-useful newest-first; text fields A→Z. The
// direction stays freely togglable — this only picks the default applied
// when the field changes, and labels the toggle so "descending" reads as
// "Newest" for dates and "Z→A" for text.
const isTextField = (f: MangaSort) => f === 'title' || f === 'author';
const defaultOrderFor = (f: MangaSort): SortOrder => (isTextField(f) ? 'asc' : 'desc');
const SORT_FIELD_LABELS: Record<MangaSort, string> = {
updated: 'Last updated',
created: 'Date added',
title: 'Title',
author: 'Author'
};
const dirOptions = $derived<{ label: string; value: SortOrder }[]>(
isTextField(sort)
? [
{ label: 'A→Z', value: 'asc' },
{ label: 'Z→A', value: 'desc' }
]
: [
{ label: 'Newest', value: 'desc' },
{ label: 'Oldest', value: 'asc' }
]
);
const dirLabel = $derived(
dirOptions.find((o) => o.value === order)?.label ?? ''
);
const sortLabel = $derived(`${SORT_FIELD_LABELS[sort]} · ${dirLabel}`);
// 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(
total != null && total > 0 ? Math.ceil(total / PAGE_SIZE) : 1
@@ -126,10 +111,11 @@
if (!browser) return;
const params = new URLSearchParams();
if (search.trim()) params.set('q', search.trim());
if (sort !== 'updated') params.set('sort', sort);
// Only persist `order` when it deviates from the field's natural
// default, so the common case keeps a clean URL.
if (order !== defaultOrderFor(sort)) params.set('order', order);
// 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 (selectedGenres.length)
params.set('genres', selectedGenres.map((g) => g.id).join(','));
@@ -163,12 +149,10 @@
// Genre objects so the chip rows render real labels.
const url = new URL($page.url);
search = url.searchParams.get('q') ?? '';
const s = url.searchParams.get('sort');
if (s === 'created' || s === 'updated' || s === 'title' || s === 'author') sort = s;
const o = url.searchParams.get('order');
sort = coerceSort(url.searchParams.get('sort'));
// Fall back to the field's natural default when `order` is absent or
// invalid, mirroring how syncUrl omits the default.
order = o === 'asc' || o === 'desc' ? o : defaultOrderFor(sort);
order = coerceOrder(url.searchParams.get('order'), sort);
const st = url.searchParams.get('status');
statusFilter = st === 'ongoing' || st === 'completed' ? st : '';
const genreIds = (url.searchParams.get('genres') ?? '')
@@ -560,13 +544,16 @@
<option value="author">Author</option>
</select>
</label>
<SegmentedControl
options={dirOptions}
value={order}
onchange={pickOrder}
ariaLabel="Sort direction"
testid="sort-order"
/>
<div class="sort">
<span>Direction</span>
<SegmentedControl
options={dirOptions}
value={order}
onchange={pickOrder}
ariaLabel="Sort direction"
testid="sort-order"
/>
</div>
</div>
</form>
@@ -585,7 +572,8 @@
onClose={() => (sortSheetOpen = false)}
testid="sort-sheet"
>
<div class="sort-options">
<p id="sort-field-heading" class="sort-section-label">Sort by</p>
<div class="sort-options" role="radiogroup" aria-labelledby="sort-field-heading">
{#each Object.entries(SORT_FIELD_LABELS) as [value, label] (value)}
<label>
<input
@@ -596,11 +584,14 @@
checked={sort === value}
onchange={() => pickSort(value as MangaSort)}
/>
<!-- aria-label duplicates the visible span text on purpose so
the e2e getByRole('radio', { name }) lookup is stable. -->
<span>{label}</span>
</label>
{/each}
</div>
<div class="sort-direction">
<p class="sort-section-label">Direction</p>
<SegmentedControl
options={dirOptions}
value={order}
@@ -609,6 +600,16 @@
testid="sort-order-mobile"
/>
</div>
{#snippet footer()}
<button
type="button"
class="primary"
onclick={() => (sortSheetOpen = false)}
data-testid="sort-done"
>
Done
</button>
{/snippet}
</Sheet>
{#if loading}
@@ -901,6 +902,26 @@
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 {
display: inline-flex;
align-items: center;