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

View File

@@ -149,14 +149,16 @@ test.describe('mobile catalog chrome', () => {
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
}) => {
let lastSortParam: string | null = null;
let lastOrderParam: string | null = null;
await mockAnonymous(page);
await mockCatalog(page, {
capture: (url) => {
lastSortParam = url.searchParams.get('sort');
lastOrderParam = url.searchParams.get('order');
}
});
await page.setViewportSize(MOBILE);
@@ -166,13 +168,22 @@ test.describe('mobile catalog chrome', () => {
await page.getByTestId('sort-chip').click();
await expect(page.getByTestId('sort-sheet')).toBeVisible();
// Use click(), not check(): the onchange handler closes the sheet
// synchronously so the radio is gone before check() can verify the
// `checked` state.
await page.getByTestId('sort-sheet').getByRole('radio', { name: /Title/ }).click();
await expect(page.getByTestId('sort-sheet')).toBeHidden();
// Picking a field reloads but keeps the sheet open so the direction
// can be adjusted in the same interaction.
await page.getByTestId('sort-sheet').getByRole('radio', { name: /^Title$/ }).click();
await expect(page.getByTestId('sort-sheet')).toBeVisible();
await expect(page).toHaveURL(/sort=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');
});
});

View File

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

View File

@@ -89,7 +89,7 @@ describe('mangas api client', () => {
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()));
await listMangas({
search: 'one piece',
@@ -99,7 +99,8 @@ describe('mangas api client', () => {
tagIds: ['t1', 't2'],
limit: 10,
offset: 20,
sort: 'title'
sort: 'title',
order: 'asc'
});
const url = fetchSpy.mock.calls[0][0] as string;
expect(url).toMatch(/\/v1\/mangas\?/);
@@ -113,6 +114,7 @@ describe('mangas api client', () => {
expect(url).toContain('limit=10');
expect(url).toContain('offset=20');
expect(url).toContain('sort=title');
expect(url).toContain('order=asc');
});
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 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 GenreRef = { id: string; name: string };
@@ -39,6 +40,7 @@ export type ListOptions = {
limit?: number;
offset?: number;
sort?: MangaSort;
order?: SortOrder;
};
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.offset != null) params.set('offset', String(opts.offset));
if (opts.sort) params.set('sort', opts.sort);
if (opts.order) params.set('order', opts.order);
const qs = params.toString();
return request<MangasPage>(`/v1/mangas${qs ? `?${qs}` : ''}`);
}

View File

@@ -7,6 +7,7 @@
listMangas,
type MangaCard as MangaCardData,
type MangaSort,
type SortOrder,
type MangaStatus
} from '$lib/api/mangas';
import { listGenres, type Genre } from '$lib/api/genres';
@@ -14,6 +15,7 @@
import Chip from '$lib/components/Chip.svelte';
import MangaCard from '$lib/components/MangaCard.svelte';
import Pager from '$lib/components/Pager.svelte';
import SegmentedControl from '$lib/components/SegmentedControl.svelte';
import Sheet from '$lib/components/Sheet.svelte';
import Search from '@lucide/svelte/icons/search';
import SlidersHorizontal from '@lucide/svelte/icons/sliders-horizontal';
@@ -25,7 +27,8 @@
let mangas: MangaCardData[] = $state([]);
let search = $state('');
let sort = $state<MangaSort>('recent');
let sort = $state<MangaSort>('updated');
let order = $state<SortOrder>('desc');
let statusFilter = $state<'' | MangaStatus>('');
let selectedGenres = $state<Genre[]>([]);
let selectedTags = $state<Tag[]>([]);
@@ -55,7 +58,37 @@
(statusFilter ? 1 : 0) + selectedGenres.length + selectedTags.length
);
const sortLabel = $derived(sort === 'title' ? 'Title (A→Z)' : 'Recent');
// 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}`);
const totalPages = $derived(
total != null && total > 0 ? Math.ceil(total / PAGE_SIZE) : 1
@@ -76,6 +109,7 @@
genreIds: selectedGenres.map((g) => g.id),
tagIds: selectedTags.map((t) => t.id),
sort,
order,
limit: PAGE_SIZE,
offset: (currentPage - 1) * PAGE_SIZE
});
@@ -92,7 +126,10 @@
if (!browser) return;
const params = new URLSearchParams();
if (search.trim()) params.set('q', search.trim());
if (sort !== 'recent') params.set('sort', sort);
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);
if (statusFilter) params.set('status', statusFilter);
if (selectedGenres.length)
params.set('genres', selectedGenres.map((g) => g.id).join(','));
@@ -127,7 +164,11 @@
const url = new URL($page.url);
search = url.searchParams.get('q') ?? '';
const s = url.searchParams.get('sort');
if (s === 'title' || s === 'recent') sort = s;
if (s === 'created' || s === 'updated' || s === 'title' || s === 'author') sort = s;
const o = url.searchParams.get('order');
// 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);
const st = url.searchParams.get('status');
statusFilter = st === 'ongoing' || st === 'completed' ? st : '';
const genreIds = (url.searchParams.get('genres') ?? '')
@@ -166,6 +207,15 @@
}
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();
}
@@ -249,12 +299,12 @@
}
function pickSort(next: MangaSort) {
if (next === sort) {
sortSheetOpen = false;
return;
}
if (next === sort) return;
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();
}
@@ -504,10 +554,19 @@
<label class="sort">
<span>Sort</span>
<select bind:value={sort} onchange={onSortChange} data-testid="sort-select">
<option value="recent">Recent</option>
<option value="title">Title (A→Z)</option>
<option value="updated">Last updated</option>
<option value="created">Date added</option>
<option value="title">Title</option>
<option value="author">Author</option>
</select>
</label>
<SegmentedControl
options={dirOptions}
value={order}
onchange={pickOrder}
ariaLabel="Sort direction"
testid="sort-order"
/>
</div>
</form>
@@ -527,28 +586,28 @@
testid="sort-sheet"
>
<div class="sort-options">
<label>
<input
type="radio"
name="sort-mobile"
value="recent"
aria-label="Recent"
checked={sort === 'recent'}
onchange={() => pickSort('recent')}
/>
<span>Recent</span>
</label>
<label>
<input
type="radio"
name="sort-mobile"
value="title"
aria-label="Title (A→Z)"
checked={sort === 'title'}
onchange={() => pickSort('title')}
/>
<span>Title (A→Z)</span>
</label>
{#each Object.entries(SORT_FIELD_LABELS) as [value, label] (value)}
<label>
<input
type="radio"
name="sort-mobile"
{value}
aria-label={label}
checked={sort === value}
onchange={() => pickSort(value as MangaSort)}
/>
<span>{label}</span>
</label>
{/each}
</div>
<div class="sort-direction">
<SegmentedControl
options={dirOptions}
value={order}
onchange={pickOrder}
ariaLabel="Sort direction"
testid="sort-order-mobile"
/>
</div>
</Sheet>
@@ -836,6 +895,12 @@
cursor: pointer;
}
.sort-direction {
margin-top: var(--space-3);
padding-top: var(--space-3);
border-top: 1px solid var(--border);
}
.icon-btn {
display: inline-flex;
align-items: center;