English

ページネーション

長い一覧のページへのリンクです。前後のページ、最初と最後のページ、今のページの隣のページを並べます。

実行結果

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: "ページ送り"
            .into(),
        previous: "前へ"
            .into(),
        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 {
            title: Doc::Components(Component::Pagination).title(site).into(),
        },
    )
    .child(
        div()
            .css(stack(rem(1)))
            .child(h2().bind_text(Docs::title()))
            .child(pager),
    )
}

アクセシビリティ

リンクはラベルを名前に持つ <nav> の中にあるので、スクリーンリーダーはそれをページのランドマークの一覧に出します。今のページへのリンクは aria-current="page" を持ちます。前後のページへのリンクは rel="prev" と rel="next" を持ち、「前へ」「次へ」を言葉で示します。最初のページでは「前へ」がリンクではなく aria-disabled="true" を持つテキストになり、最後のページでは「次へ」が同じようになるので、Tab では飛ばされます。省いたページの代わりの … は支援技術から隠します。

キー動作
Tab次のリンクにフォーカスを移します。
Enterフォーカスのあるリンクの先に移ります。

pagination は今のページ、ページ数、ページへのリンクを返す関数、各部分の言葉を受け取ります。

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

ページは 1 から数えます。リンクは前後のページ、最初と最後のページ、今のページの隣のページで、省いたページは … で表します。… が 1 ページだけを表すことになる場合は、代わりにそのページを表示します。

10 ページ中の current表示されるページのリンク
11、2、…、10
41、2、3、4、5、…、10
51、…、4、5、6、…、10
101、…、9、10

link はルートの link_with で作る Link を返すので、どのページもアプリケーションの URL になります。URL を自分で組み立てるクロージャは String を返すので、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(),
);

リンクは普通の <a> なので、たどるとサーバーからその URL のページが読み込まれ、サーバーがそのページの行と、そのページ用のページネーションを描画します。

言葉

PaginationText は、<nav> の名前と前後のリンクの言葉を持ちます。PaginationText::default() は英語なので、ほかの言語のページは自分の言葉を渡します。

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,
}

フィールドはただの文字列で、すべてのフィールドを書く必要があるので、検査されるのは書き忘れがないことだけです。すべてのコンポーネントの言葉をまとめて渡す方法は ほかの言語の文言 で説明します。

出力される HTML

PRODUCTS.link_with(&page) のリンクで 10 ページ中の 5 ページ目を表示すると、次のように描画されます。

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

1 ページ目では、最初の項目が同じ矢印と Previous を持つ <span aria-disabled="true"> になり、href はありません。

検査されないこと

current と count はただの数です。current が 0 か count より大きいと、pagination を呼んだ時点でパニックします。そのため、ページ番号を URL から受け取るハンドラは先にそれを確かめ、下の例のように、最後より後ろのページには 404 を返します。

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());

検索結果が 0 件のときのように count が 0 の場合は 1 ページとして表示し、その 1 ページ目は正しい値として扱われます。link が n に対してページ n の URL を返すかどうかは検査されないので、引数を使わないクロージャでは、どの番号も同じ href になります。

例: 商品の一覧

ハンドラはページ数を数え、範囲外のページには 404 を返し、そのページの商品とその下のリンクを描画します。

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))
}

行をブラウザやサーバーでページに分ける表は、専用のページ送りのボタンを持ちます。これは 絞り込みとページ分け と サーバーテーブル で説明します。次の データテーブル では型の付いた列の下に行を並べます。