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

@@ -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

@@ -17,14 +17,69 @@
ariaLabel: string;
testid?: string;
} = $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>
<div class="segmented" role="radiogroup" aria-label={ariaLabel} data-testid={testid}>
{#each options as opt (opt.value)}
<!-- Keydown is delegated here; focus lives on the child radios via roving
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
bind:this={buttons[i]}
type="button"
role="radio"
aria-checked={opt.value === value}
tabindex={opt.value === value ? 0 : -1}
class="seg"
class:active={opt.value === value}
onclick={() => {

View File

@@ -1,5 +1,5 @@
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';
afterEach(() => cleanup());
@@ -50,4 +50,74 @@ describe('SegmentedControl', () => {
});
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;
}