日本語

Pagination

Links to the pages of a long list: the page before and after, the first and the last, and the pages next to the current one.

Result

pagination.rs
use hypersig::html::{div, h2};
use hypersig::style::pattern::stack;
use hypersig::style::value::rem;
use hypersig::{Page, Rest, Signals};
use hypersig_ui::{PaginationText, pagination};
use serde::{Deserialize, Serialize};

use crate::doc::{Component, Doc};
use crate::{PAGE, Site};

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Docs {
    /// The title of the page the demo stands on.
    title: String,
}

/// The component pages the pagination steps through, this page fifth.
const PAGES: [Component; 9] = [
    Component::Tabs,
    Component::Accordion,
    Component::Collapsible,
    Component::Card,
    Component::Pagination,
    Component::Separator,
    Component::Navigation,
    Component::Breadcrumb,
    Component::DataTable,
];

/// The path of `doc` inside this site, as `PAGE` takes it.
fn at(site: Site, doc: Doc) -> Rest {
    Rest::parse(doc.url(site).trim_start_matches('/'))
        .expect("a component's page has a directory without `.` or `..` parts")
}

pub(super) fn page() -> Page<Docs> {
    let text = PaginationText {
        label: "Pagination"
            .into(),
        previous: "Previous"
            .into(),
        next: "Next"
            .into(),
    };
    let pager = pagination(
        5,
        9,
        |page| PAGE.link_with(at(site, Doc::Components(PAGES[usize::try_from(page).expect("a page number fits in usize") - 1]))),
        &text,
    );
    Page::new(
        "Docs",
        Docs {
            title: Doc::Components(Component::Pagination).title(site).into(),
        },
    )
    .child(
        div()
            .css(stack(rem(1)))
            .child(h2().bind_text(Docs::title()))
            .child(pager),
    )
}

Accessibility

The links sit in a <nav> named by its label, so a screen reader lists them among the page's landmarks. The link to the current page carries aria-current="page". The links to the page before and after carry rel="prev" and rel="next" and say Previous and Next in words. On the first page, Previous is text marked aria-disabled="true" rather than a link, and so is Next on the last, so Tab skips it. The … that stands for the pages left out is hidden from assistive technology.

KeyWhat it does
TabMoves focus to the next link.
EnterFollows the focused link.

pagination takes the current page, the number of pages, a function that returns the link to a page, and the words of its parts:

pub fn pagination<S>(
    current: u32,
    count: u32,
    link: impl Fn(u32) -> Link<S>,
    text: &PaginationText,
) -> El<S>;

Pages are counted from 1. The links are the page before and after, the first and the last page, and the pages next to the current one, with … for the pages left out. Where … would stand for one page, that page is shown instead.

current of 10 pagesThe page links shown
11, 2, …, 10
41, 2, 3, 4, 5, …, 10
51, …, 4, 5, 6, …, 10
101, …, 9, 10

link returns a Link, which a route builds with link_with, so each page is a URL of the application. A closure that formats the URL itself returns a String, which is E0308:

use hypersig::Signals;
use hypersig_ui::{PaginationText, pagination};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Catalog {}

// error[E0308]: mismatched types: expected `Link<Catalog>`, found `String`
let pager = pagination::<Catalog>(
    3,
    5,
    |page| format!("/products/{page}"),
    &PaginationText::default(),
);

The links are plain <a> elements, so following one loads the page at that URL from the server, which renders the rows of that page and the pagination for it.

The words

PaginationText holds the name of the <nav> and the words of the two links. PaginationText::default() is English, so a page in another language passes its own:

pub struct PaginationText {
    /// The name of the `<nav>`, "Pagination".
    pub label: String,
    /// The link to the page before, "Previous".
    pub previous: String,
    /// The link to the page after, "Next".
    pub next: String,
}

The fields are plain text and every field must be given, so the only check is that none is forgotten. Text in other languages covers passing the words of every component together.

The HTML

Page 5 of 10, with links from PRODUCTS.link_with(&page), renders as:

<nav aria-label="Pagination">
  <ul>
    <li><a href="/products/4" rel="prev"><svg aria-hidden="true" …></svg><span>Previous</span></a></li>
    <li><a href="/products/1">1</a></li>
    <li aria-hidden="true">…</li>
    <li><a href="/products/4">4</a></li>
    <li><a href="/products/5" aria-current="page">5</a></li>
    <li><a href="/products/6">6</a></li>
    <li aria-hidden="true">…</li>
    <li><a href="/products/10">10</a></li>
    <li><a href="/products/6" rel="next"><span>Next</span><svg aria-hidden="true" …></svg></a></li>
  </ul>
</nav>

On page 1, the first item is <span aria-disabled="true"> holding the same arrow and Previous, with no href.

What is not checked

current and count are plain numbers. A current of 0, or above count, panics when pagination is called, so a handler whose page number comes from the URL checks it first and answers 404 for a page past the end, as the example below does:

use hypersig::{Route, Signals};
use hypersig_ui::{PaginationText, pagination};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Catalog {}

hypersig::routes! {
    fn pages(Router<()>);
    const PRODUCTS: Route<u32> = "/products/{page}" => products;
}

// Panics: the current page is between 1 and the number of pages, not 6 of 5.
let pager = pagination::<Catalog>(6, 5, |n| PRODUCTS.link_with(&n), &PaginationText::default());

A count of 0, as for a search that found nothing, shows one page, and page 1 of it is valid. Nothing checks that link returns the URL of page n for n, so a closure that ignores its argument gives every number the same href.

Example: a product list

The handler counts the pages, answers 404 for a page outside them, and renders the products of the page with the links under them:

use hypersig::html::{li, ul};
use hypersig::{Page, Route, Signals};
use hypersig_ui::{PaginationText, pagination};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Catalog {}

hypersig::routes! {
    fn pages(Router<()>);
    const PRODUCTS: Route<u32> = "/products/{page}" => products;
}

const PER_PAGE: usize = 20;

async fn products((): (), page: u32) -> Option<Page<Catalog>> {
    let all: Vec<String> = (1..=95).map(|n| format!("Product {n}")).collect();
    let count = u32::try_from(all.len().div_ceil(PER_PAGE)).ok()?;
    // A page outside 1 to `count` answers 404 here, where `pagination` would panic.
    if page == 0 || page > count.max(1) {
        return None;
    }
    let start = (page as usize - 1) * PER_PAGE;
    let shown = all.iter().skip(start).take(PER_PAGE).map(|name| li().text(name));
    let pager = pagination(page, count, |n| PRODUCTS.link_with(&n), &PaginationText::default());
    Some(Page::new("Products", Catalog {}).child(ul().children(shown)).child(pager))
}

A table that pages its rows in the browser or on the server has its own page buttons, which Filtering and pages and Server table cover. Next, Data table lists rows under typed columns.