日本語

Selecting and expanding rows

Checkboxes that keep the keys of the selected rows in a list signal, and buttons that open a row's details under it.

Result

table_selection.rs
use hypersig::html::{div, p, span};
use hypersig::style::pattern::stack;
use hypersig::style::value::rem;
use hypersig::{NumberFormat, Page, Signals};
use hypersig_ui::{Column, DataTable, TableState, TableText};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Payment {
    id: i32,
    email: String,
    amount: f64,
    note: String,
}

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Ledger {
    payments: Vec<Payment>,
    chosen: Vec<i32>,
    open: Vec<i32>,
    table: TableState,
}

pub(super) fn page() -> Page<Ledger> {
    let payments = [
        (
            "ken99@example.com",
            316.0,
            "Paid by card.",
        ),
        (
            "abe45@example.com",
            242.0,
            "Refund requested on Monday.",
        ),
        (
            "monserrat44@example.com",
            837.0,
            "Paid by bank transfer.",
        ),
        (
            "silas22@example.com",
            874.0,
            "Waiting for the bank.",
        ),
    ]
    .into_iter()
    .zip(1..)
    .map(|((email, amount, note), id)| Payment {
        id,
        email: email.to_owned(),
        amount,
        note: note.to_owned(),
    })
    .collect();
    let table = DataTable::new(
        "Payments",
        Ledger::table(),
        Ledger::payments(),
        |payment| payment.at(Payment::id()),
    )
    .selectable(Ledger::chosen(), |payment| payment.at(Payment::id()))
    .expandable(
        Ledger::open(),
        |payment| payment.at(Payment::id()),
        |payment| p().bind_text(payment.at(Payment::note())),
    )
    .text(TableText {
        select_row: "Select row"
            .to_owned(),
        select_all: "Select all rows"
            .to_owned(),
        expand_row: "Show row details"
            .to_owned(),
        ..TableText::default()
    })
    .column(Column::text(
        "Email",
        Payment::email(),
    ))
    .column(Column::formatted(
        "Amount",
        Payment::amount(),
        NumberFormat::new().digits(2).prefix("$"),
    ));
    Page::new(
        "Payments",
        Ledger {
            payments,
            chosen: Vec::new(),
            open: Vec::new(),
            table: TableState::default(),
        },
    )
    .child(
        div().css(stack(rem(1))).child(table).child(
            p().child(span().bind_text(Ledger::chosen().len().to_text()))
                .text(" selected"),
        ),
    )
}

Accessibility

Each row's checkbox is a native <input type="checkbox"> named by TableText::select_row. The header checkbox follows the WAI-ARIA checkbox pattern: a <button> with role="checkbox" whose aria-checked is true while every row is selected, mixed while some are, and false while none is. It is a button because a native checkbox's mixed state is a property that no attribute sets, and the first HTML could not show it.

The button at the start of an expandable row is named by TableText::expand_row and carries aria-expanded, as the WAI-ARIA disclosure pattern asks, so a screen reader announces whether the row's details are shown.

KeyWhat it does
SpaceToggles the focused checkbox. On the header checkbox, selects every row, or clears them once all are selected.
Enter, SpaceOn the button at the start of a row, shows or hides the row's details.

Selecting rows

selectable adds a first column of checkboxes, which keep the key of each selected row in a list signal:

impl<S: 'static, T: 'static> DataTable<S, T> {
    pub fn selectable<K: PartialEq + 'static, E: IntoExpr<S, K>>(
        self,
        selected: Sig<S, Vec<K>>,
        key: impl Fn(Item<S, T>) -> E + 'static,
    ) -> Self;
}

The keys live in a signal of the page, apart from the rows, so the row type needs no field for the selection, and a patch of the rows leaves the selection as it was. Any statement reads them, such as an action call that takes Ledger::chosen() as its argument, and the handler receives the keys as a Vec. key must return the type the list holds, so a key of another type is E0277:

use hypersig::Signals;
use hypersig_ui::{DataTable, TableState};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Payment {
    id: i32,
    email: String,
}

#[derive(Signals, Serialize, Deserialize)]
struct Ledger {
    payments: Vec<Payment>,
    chosen: Vec<i32>,
    table: TableState,
}

// error[E0277]: `Sig<Ledger, String, Local>` is not an expression of type `i32`
//     on the page whose signals are `Ledger`
let table = DataTable::new("Payments", Ledger::table(), Ledger::payments(), |payment| {
    payment.at(Payment::id())
})
.selectable(Ledger::chosen(), |payment| payment.at(Payment::email()));

The header checkbox selects every row of the list, including rows the filter or the page hides, and a press while all are selected clears them. A selected row is drawn on the muted background.

Expanding rows

expandable adds a first column of buttons that show a row's details in a row of their own under it, across every column:

impl<S: 'static, T: 'static> DataTable<S, T> {
    pub fn expandable<K: PartialEq + 'static, E: IntoExpr<S, K>>(
        self,
        expanded: Sig<S, Vec<K>>,
        key: impl Fn(Item<S, T>) -> E + 'static,
        details: impl Fn(Item<S, T>) -> El<S> + 'static,
    ) -> Self;
}

expanded keeps the keys of the open rows as selected does, and its key is checked against the list's type the same way. details builds the element from the row. Each row and its details are a <tbody> of their own, so the two move together when the rows are sorted. A table with both has the expand buttons first, then the checkboxes.

The HTML

The table of the example below, with the second payment selected, renders its header and first row as:

<thead>
  <tr>
    <td></td>
    <th scope="col">
      <button type="button" role="checkbox" aria-label="Select all rows" aria-checked="mixed">
        <span aria-hidden="true"><svg …></svg><svg …></svg></span>
      </button>
    </th>
    <th scope="col">Email</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td><button type="button" aria-label="Show row details" aria-expanded="false"><svg …></svg></button></td>
    <td><span><input aria-label="Select row" type="checkbox"><span aria-hidden="true"><svg …></svg></span></span></td>
    <td><span>ken99@example.com</span></td>
  </tr>
  <tr><td colspan="3"><p>Paid by card.</p></td></tr>
</tbody>

The second row's checkbox carries checked. The details row is in the HTML and hidden until its button is pressed.

What is not checked

A selected key stays in the list after its row leaves the table, until the header clears the selection or the page removes the key, so a handler that receives the keys checks them against its own data. The keys are compared as JSON, as each_keyed compares them. Selecting with the header includes rows the visitor cannot see on the current page or through the filter.

Example: refunding selected payments

The button sends the selected ids to an action, which clears the selection in its answer:

use hypersig::html::{div, p};
use hypersig::{Action, Page, Patches, Signals};
use hypersig_ui::{ButtonSize, ButtonVariant, Column, DataTable, TableState, button};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Payment {
    id: i32,
    email: String,
    note: String,
}

#[derive(Signals, Serialize, Deserialize)]
struct Ledger {
    payments: Vec<Payment>,
    chosen: Vec<i32>,
    open: Vec<i32>,
    table: TableState,
}

hypersig::routes! {
    fn actions(Router<()>);
    action REFUND: Action<Ledger, Vec<i32>> = post "/refunds" => refund;
}

/// Receives the ids of the selected payments.
async fn refund((): (), ids: Vec<i32>) -> Patches<Ledger> {
    // Refund each payment in `ids` here, then clear the selection.
    let _ = ids;
    Ledger::chosen().patch(Vec::new()).into()
}

let table = DataTable::new("Payments", Ledger::table(), Ledger::payments(), |payment| {
    payment.at(Payment::id())
})
.selectable(Ledger::chosen(), |payment| payment.at(Payment::id()))
.expandable(
    Ledger::open(),
    |payment| payment.at(Payment::id()),
    |payment| p().bind_text(payment.at(Payment::note())),
)
.column(Column::text("Email", Payment::email()));

let refund_button = button(ButtonVariant::Destructive, ButtonSize::Default)
    .on_click(REFUND.call_with(Ledger::chosen()))
    .text("Refund selected");

let payments = vec![
    Payment { id: 1, email: "ken99@example.com".into(), note: "Paid by card.".into() },
    Payment { id: 2, email: "abe45@example.com".into(), note: "Refund requested.".into() },
];
let state = Ledger { payments, chosen: vec![2], open: Vec::new(), table: TableState::default() };
let html = Page::new("Payments", state)
    .child(div().child(table).child(refund_button))
    .render();

Next, Server table lets the server filter, sort, and page the rows.