Sorting a table
Column headers that sort the rows of a table in the browser, ascending and then descending.
Result
use hypersig::{NumberFormat, Page, Signals};
use hypersig_ui::{Column, DataTable, TableState};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Payment {
id: i32,
email: String,
amount: f64,
}
#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Ledger {
payments: Vec<Payment>,
table: TableState,
}
pub(super) fn page() -> Page<Ledger> {
let payments = [
("ken99@example.com", 316.0),
("abe45@example.com", 242.0),
("monserrat44@example.com", 837.0),
("silas22@example.com", 874.0),
("carmella@example.com", 242.0),
]
.into_iter()
.zip(1..)
.map(|((email, amount), id)| Payment {
id,
email: email.to_owned(),
amount,
})
.collect();
let table = DataTable::new(
"Payments",
Ledger::table(),
Ledger::payments(),
|payment| payment.at(Payment::id()),
)
.column(Column::number("Id", Payment::id()))
.sortable_column(
Column::text(
"Email",
Payment::email(),
),
|payment| payment.at(Payment::email()),
)
.sortable_column(
Column::formatted(
"Amount",
Payment::amount(),
NumberFormat::new().digits(2).prefix("$"),
),
|payment| payment.at(Payment::amount()),
);
Page::new(
"Payments",
Ledger {
payments,
table: TableState::default(),
},
)
.child(table)
}Accessibility
A sortable column's header holds a native <button> with the header's text, and the <th> carries aria-sort, which is ascending, descending, or none. A screen reader reads the header as a button and announces the direction the column is sorted in. The arrows beside the text are drawn for sighted visitors and hidden from assistive technology.
| Key | What it does |
|---|---|
| Tab | Moves focus to the next sortable header. |
| Enter, Space | On a header, sorts the rows by that column: ascending, or descending where the column is sorted ascending. |
A sortable column
sortable_column adds a column, as column does, with the key its header sorts the rows by:
impl<S: 'static, T: 'static> DataTable<S, T> {
pub fn sortable_column<K: Comparable, E: IntoExpr<S, K>>(
self,
column: Column<S, T>,
key: impl Fn(Item<S, T>) -> E + 'static,
) -> Self;
}The key is usually the field the column shows, but it can be any expression of the row, such as a lower-cased name. The first press on a header sorts the rows ascending, a press on the column sorted ascending sorts it descending, and a press on any other state sorts ascending again. The browser sorts without a request, and the sort is stable: rows with equal keys keep their order, so sorting by one column and then by another orders the rows by the second and, among equal values, by the first.
K must be Comparable, which i32, i64, f64, and String implement, because the browser orders only numbers and strings. A key of another type, such as a bool, is E0277:
use hypersig::Signals;
use hypersig_ui::{Column, DataTable, TableState};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Payment {
id: i32,
email: String,
refunded: bool,
}
#[derive(Signals, Serialize, Deserialize)]
struct Ledger {
payments: Vec<Payment>,
table: TableState,
}
// error[E0277]: the trait bound `bool: Comparable` is not satisfied
let table = DataTable::new("Payments", Ledger::table(), Ledger::payments(), |payment| {
payment.at(Payment::id())
})
.sortable_column(Column::text("Email", Payment::email()), |payment| {
payment.at(Payment::refunded())
});Sorting reorders the list signal itself, not only the table. Anything else on the page that reads the list, such as a chart of the same rows, follows the new order.
The HTML
The header row of the example below, before any sort, renders as follows. The <svg> elements are the three arrows, of which the browser shows the one for the current direction:
<tr>
<th scope="col">Id</th>
<th scope="col" aria-sort="none">
<button type="button"><span>Email</span><svg …></svg><svg …></svg><svg …></svg></button>
</th>
<th scope="col" aria-sort="none">
<button type="button"><span>Amount</span><svg …></svg><svg …></svg><svg …></svg></button>
</th>
</tr>A press on Email turns its aria-sort to ascending, leaves Amount at none, and moves the <tr> elements of the body into the new order.
The sort in the state
The header writes which column is sorted, and whether descending, into the table's TableState. Those two fields are private. SortOrder names the direction, and two methods write and read the sort by a key with #[derive(Segment)]:
pub enum SortOrder {
Ascending,
Descending,
}
impl TableState {
pub fn with_sorting<K: Segment>(self, key: &K, order: SortOrder) -> Self;
pub fn sorting<K: Segment>(&self) -> Option<(K, SortOrder)>;
}use hypersig::Segment;
use hypersig_ui::{SortOrder, TableState};
use serde::{Deserialize, Serialize};
/// The columns a `ServerTable` sorts by.
#[derive(Segment, Serialize, Deserialize, Debug, PartialEq)]
enum By {
Email,
Amount,
}
// The first state of a page whose rows arrive sorted by amount, largest first.
let state = TableState::default().with_sorting(&By::Amount, SortOrder::Descending);
assert_eq!(state.sorting::<By>(), Some((By::Amount, SortOrder::Descending)));
// An unsorted state has no sort to read.
assert_eq!(TableState::default().sorting::<By>(), None);These keys are the ones a ServerTable's headers write, where the server sorts the rows and reads the sort back with sorting. A DataTable's headers do not name their columns by such a key, so with_sorting does not mark one of its headers, and sorting reads None from its state for an enum of keys. A page that sends a DataTable its rows already sorted shows every header at aria-sort="none" until the visitor sorts.
What is not checked
The order holds until the list changes. A patch from the server replaces the list in the server's order, and the header still marks the last sort, so a page whose handler patches the rows sorts them the same way on the server or accepts the mismatch. Nothing checks that the key matches what the column shows: a column of names sorted by an id sorts by the id.
Example: sortable payments
Email and Amount sort the rows, and Id does not:
use hypersig::{NumberFormat, Page, Signals};
use hypersig_ui::{Column, DataTable, TableState};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Payment {
id: i32,
email: String,
amount: f64,
}
#[derive(Signals, Serialize, Deserialize)]
struct Ledger {
payments: Vec<Payment>,
table: TableState,
}
const DOLLARS: NumberFormat = NumberFormat::new().digits(2).prefix("$");
let table = DataTable::new("Payments", Ledger::table(), Ledger::payments(), |payment| {
payment.at(Payment::id())
})
.column(Column::number("Id", Payment::id()))
.sortable_column(Column::text("Email", Payment::email()), |payment| {
payment.at(Payment::email())
})
.sortable_column(Column::formatted("Amount", Payment::amount(), DOLLARS), |payment| {
payment.at(Payment::amount())
});
let payments = vec![
Payment { id: 1, email: "ken99@example.com".into(), amount: 316.0 },
Payment { id: 2, email: "abe45@example.com".into(), amount: 242.0 },
];
let html = Page::new("Payments", Ledger { payments, table: TableState::default() })
.child(table)
.render();Next, Filtering and pages shows part of the rows at a time.