Sorting & pagination UIs
Four small helpers in @qubeejs/core do the arithmetic every list UI repeats. They are plain
functions, so they work in Server Components too.
| Helper | Answers |
|---|---|
toggleSort(sorts, field, { multiple }) |
the sorts after a click on a column header |
getAriaSort(sorts, field) |
the header’s aria-sort value |
getPageWindow(page, lastPage, { boundaries, siblings }) |
which page numbers to show, and where the gaps go |
getPageRange(result) |
the from, to and total behind “21–40 of 57” |
Sortable headers
Section titled “Sortable headers”useQubeeList wraps toggleSort for you, but only when the list declares exactly one sortParam.
field is typed to the fields that param allows. A click on the primary sort flips its direction;
a click on any other column sorts by it, ascending.
import { getAriaSort } from '@qubeejs/core';import type { QubeeListHandle } from '@qubeejs/react';import type { ReactNode } from 'react';
import type { articleList } from './article-list';
type SortHeaderProps = { children: ReactNode; field: 'publishedAt' | 'title'; list: QubeeListHandle<typeof articleList>;};
/** The arrow for the direction a column is sorted in, if it is the primary sort. */const ARROWS = { ascending: ' ▲', descending: ' ▼', none: '' } as const;
/** * A column header that sorts the list by its field: a click sorts ascending, * the next one flips it; a shift-click adds the field to the sorts in place. */export function SortHeader({ children, field, list }: SortHeaderProps) { const direction = getAriaSort(list.state.sort, field);
return ( <th aria-sort={direction} scope="col"> <button onClick={(event) => list.toggleSort(field, { multiple: event.shiftKey })} type="button"> {children} <span aria-hidden="true">{ARROWS[direction]}</span> </button> </th> );}- One column carries a direction. ARIA allows a single sorted column, so
getAriaSortreports a direction for the primary sort and'none'for the others. - A plain click sorts by one field. It flips the direction when the field is the primary sort. Any other field — unsorted, or a secondary sort — starts ascending and replaces the other sorts.
- Shift-click sorts by several fields.
{ multiple: true }keeps the other sorts and flips the field in place, wherever it is, or appends it ascending. The URL reads?sort=-publishedAt,title.
A page window
Section titled “A page window”getPageWindow returns page numbers and 'gap' markers, always the same number of them for a
given last page, so the buttons do not jump as the reader pages:
getPageWindow(1, 12); // [1, 2, 3, 4, 5, 'gap', 12]getPageWindow(5, 12); // [1, 'gap', 4, 5, 6, 'gap', 12]getPageWindow(12, 12); // [1, 'gap', 8, 9, 10, 11, 12]A gap never hides a single page: that page’s number is shown instead. boundaries sets how many
pages stay at each end and siblings how many sit beside the current one; both default to 1.
import { getPageWindow } from '@qubeejs/core';import type { QubeeListHandle } from '@qubeejs/react';import type { MouseEvent } from 'react';
import type { articleList } from './article-list';import { isPlainClick } from './plain-click';
type PaginationBarProps = { /** The last page the API reported; 1 until the first page arrives. */ lastPage: number; list: QubeeListHandle<typeof articleList>;};
/** Previous, the page window with its gaps, and next — every page a real link. */export function PaginationBar({ lastPage, list }: PaginationBarProps) { const { page } = list.state;
/** Navigate in place on a plain click; leave any other click to the browser. */ const goTo = (target: number) => (event: MouseEvent<HTMLAnchorElement>) => { if (!isPlainClick(event)) { return; }
event.preventDefault(); list.setPage(target); };
return ( <nav aria-label="Pagination"> <ul> <li> {page > 1 ? ( <a aria-label="Previous page" href={list.href({ page: page - 1 })} onClick={goTo(page - 1)}> ‹ </a> ) : ( <span aria-hidden="true">‹</span> )} </li> {getPageWindow(page, lastPage).map((item, index) => ( <li key={item === 'gap' ? `gap-${index}` : item}> {item === 'gap' ? ( <span aria-hidden="true">…</span> ) : ( <a aria-current={item === page ? 'page' : undefined} aria-label={`Page ${item}`} href={list.href({ page: item })} onClick={goTo(item)} > {item} </a> )} </li> ))} <li> {page < lastPage ? ( <a aria-label="Next page" href={list.href({ page: page + 1 })} onClick={goTo(page + 1)}> › </a> ) : ( <span aria-hidden="true">›</span> )} </li> </ul> </nav> );}Every page is a real link — list.href({ page }) — so it opens in a new tab when asked to. A plain
click navigates in place instead:
import type { MouseEvent } from 'react';
/** * Whether a click on a link should navigate in place: the primary button, no * modifier key. Anything else — a middle click, a ⌘-click — is left to the * browser, which opens the href in a new tab. */export function isPlainClick(event: MouseEvent<HTMLAnchorElement>): boolean { return event.button === 0 && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey;}“21–40 of 57”
Section titled ““21–40 of 57””getPageRange reads the counts the backend reported and works out the ones it left out. The words,
the dash and the language stay yours:
import { getPageRange, type PaginatedResult } from '@qubeejs/core';
import type { Article } from './article-list';
/** "21–40 of 57 articles" — or "21–40 articles" when the API reports no total. */export function ResultRange({ result }: { result: PaginatedResult<Article> }) { const { from, to, total } = getPageRange(result);
if (to === 0) { return <p role="status">No articles match.</p>; }
return ( <p role="status"> {from === to ? from : `${from}–${to}`} {total === null ? ' articles' : ` of ${total} articles`} </p> );}When a backend reports no total — a cursor-paged API, say — total is null, and the example
prints “21–40 articles”.
Where the last page comes from
Section titled “Where the last page comes from”Only a response knows the last page. getPageWindow(page, lastPage) takes a number, so pass
result?.lastPage ?? 1 — lastPage is null until a response reports it.
A missing or unknown lastPage counts as 1: the window collapses to [1], without even the current
page. A backend that does not report a page count cannot drive a page window; give it previous and
next links instead, and stop when a page comes back empty or short.