日本語

Server table

A table whose filter, sort, and page go to an action, which answers with one page of rows.

This page has no live demo, because the site is static files with no server to answer the action. The code and the HTTP below are what an application runs.

Accessibility

A ServerTable renders the same <table>, filter field, sortable headers with aria-sort, checkboxes, and page buttons as a Data table, and takes the same keys. The range of rows shown sits in an aria-live="polite" paragraph, so a screen reader reads the new range once the server's answer arrives.

KeyWhat it does
Enter, SpaceOn a sortable header, asks the server for the rows sorted by that column. On a page button, asks for that page.
SpaceToggles the focused checkbox. On the header checkbox, selects or clears the rows of the page shown.

Building the table

ServerTable::new takes what DataTable::new takes and, last, load: the statement that fetches rows, which is a call to an action that receives the table's TableState:

impl<S: 'static, T: 'static> ServerTable<S, T> {
    pub fn new<K: 'static, E: IntoExpr<S, K>>(
        label: impl Into<String>,
        state: Sig<S, TableState>,
        rows: Sig<S, Vec<T>>,
        key: impl FnOnce(Item<S, T>) -> E + 'static,
        load: impl IntoStmt<S>,
    ) -> Self;
    pub fn column(self, column: Column<S, T>) -> Self;
    pub fn sortable_column<K: Segment>(self, column: Column<S, T>, key: &K) -> Self;
    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;
    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;
    pub fn filter(self, label: impl Into<String>) -> Self;
    pub fn paginate(self, size: i32, total: Sig<S, i32>) -> Self;
    pub fn text(self, text: TableText) -> Self;
    pub fn max_height(self, height: Length) -> Self;
    pub fn render(self) -> El<S>;
}

The list signal holds only the rows shown, and the browser counts no rows, so its work per change grows with the rows of one page, however many the server holds. The controls write the TableState and then run load:

MethodWhat the control does
sortable_columnThe header writes key and the direction into the state, returns to the first page, and runs load.
filterOnce typing pauses, the field returns to the first page and runs load. Its text is query, which the server filters by.
paginateThe buttons move page by one and run load. The range reads first–last / total, with total from a signal the server writes.
selectableThe keys stay in their signal when the page changes, so a row selected on one page stays selected on the next. The header checkbox selects or clears the rows of the page shown.

A sortable column takes its key as a value of a type with #[derive(Segment)], usually an enum of the columns, which the server reads back from the state. The headers and the handler's match then name the columns with one type. A key that is not a Segment, such as a string, is E0277:

use hypersig::{Action, Patches, Signals};
use hypersig_ui::{Column, ServerTable, TableState};
use serde::{Deserialize, Serialize};

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

#[derive(Signals, Serialize, Deserialize)]
struct Users {
    users: Vec<User>,
    table: TableState,
}

hypersig::routes! {
    fn actions(Router<()>);
    action LOAD: Action<Users, TableState> = post "/users/rows" => load;
}

// error[E0277]: `&str` cannot be one segment of a URL's path
let table = ServerTable::new(
    "Users",
    Users::table(),
    Users::users(),
    |user| user.at(User::id()),
    LOAD.call_with(Users::table()),
)
.sortable_column(Column::text("Email", User::email()), &"email");

What the handler receives

The action is an Action<S, TableState>, and the table calls it with LOAD.call_with(Users::table()), so the browser sends the table's state as the arguments. After the visitor typed ada, sorted Email descending, and moved to the second page, the browser's network tab shows:

POST /users/rows
accept: text/event-stream
hypersig-call: 1
content-type: application/json

{"query":"ada","page":1,"sort":"Email","descending":true}

The handler receives it deserialized as a TableState: query and page are public fields, and TableState::sorting reads the sort back as the key's type and a SortOrder. Action::request builds the same request for a test:

use hypersig::{Action, Patches, Segment, Signals};
use hypersig_ui::{SortOrder, TableState};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Users {
    table: TableState,
}

#[derive(Segment, Serialize, Deserialize)]
enum By {
    Email,
}

hypersig::routes! {
    fn actions(Router<()>);
    action LOAD: Action<Users, TableState> = post "/users/rows" => load;
}

// The state after the visitor typed "ada", sorted by email descending,
// and moved to the second page.
let mut state = TableState::default().with_sorting(&By::Email, SortOrder::Descending);
state.query = "ada".into();
state.page = 1;
let request = LOAD.request(&state);
assert_eq!(request.method(), "POST");
assert_eq!(request.uri(), "/users/rows");

What the handler returns

The handler answers with a patch of the list signal holding the rows of the page the state names, and, for a paged table, a patch of the total, the number of rows that pass the filter:

async fn load((): (), state: TableState) -> Patches<Users> {
    let (rows, total) = query(&everyone(), &state);
    Users::users().patch(rows).and(Users::total().patch(total)).into()
}

The browser replaces the rows and the range when the answer arrives. Use the same query to render the page's first rows, as the example below does, so the first HTML and every later answer agree. Patches covers what an answer can hold.

The HTML

The table of the example below, first rendered sorted by Id, renders the header of that column marked and the range from total:

<div>
  <input type="search" aria-label="Filter emails" placeholder="Filter emails" value="">
  <div>
    <table aria-label="Users">
      <thead>
        <tr>
          <th scope="col" aria-sort="ascending"><button type="button"><span>Id</span>…</button></th>
          <th scope="col" aria-sort="none"><button type="button"><span>Email</span>…</button></th>
        </tr>
      </thead>
      <tbody>
        <tr><td><span>1</span></td><td><span>user1@example.com</span></td></tr>
        …
      </tbody>
    </table>
  </div>
  <div>
    <p aria-live="polite">1–10 / 42</p>
    <button type="button" aria-label="Previous page" disabled>…</button>
    <button type="button" aria-label="Next page">…</button>
  </div>
</div>

Keeping the state in the URL

To let a reload or a shared link show the same rows, give the page a route whose search parameters are the application's own struct with #[derive(Search)] and Option fields, so the address without a query string still loads. The page handler builds the first TableState from it with with_sorting, and the action answers with Patches::replace_url of the URL its state names. TableState itself is not a search struct, because a URL that lacks one of its fields would get a 400. Search parameters covers the route.

What is not checked

What the server does with the state is the application's code, which the compiler does not check against the table. The handler answers with at most size rows of the page the state names, and a total that counts every row passing the filter. A handler that returns more rows shows them all, and a wrong total shows a wrong range and enables or disables the next-page button wrongly. A page past the last row shows no rows until the visitor goes back.

page and query come from the browser, so a handler treats them as input: a negative or very large page must not overflow its arithmetic, as saturating_mul keeps it from doing in the example.

Example: 42 users, ten at a time

One query function serves both the first render and the action:

use hypersig::{Action, Page, Patches, Segment, Signals};
use hypersig_ui::{Column, ServerTable, SortOrder, TableState};
use serde::{Deserialize, Serialize};

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

#[derive(Signals, Serialize, Deserialize)]
struct Users {
    users: Vec<User>,
    total: i32,
    table: TableState,
}

/// The columns the server sorts by, shared by the headers and the handler.
#[derive(Segment, Serialize, Deserialize)]
enum By {
    Id,
    Email,
}

const PER_PAGE: i32 = 10;

hypersig::routes! {
    fn actions(Router<()>);
    action LOAD: Action<Users, TableState> = post "/users/rows" => load;
}

/// The rows of the page `state` names, and how many rows pass its filter.
fn query(all: &[User], state: &TableState) -> (Vec<User>, i32) {
    let needle = state.query.trim().to_lowercase();
    let mut rows: Vec<User> =
        all.iter().filter(|user| user.email.contains(&needle)).cloned().collect();
    if let Some((by, order)) = state.sorting::<By>() {
        match by {
            By::Id => rows.sort_by_key(|user| user.id),
            By::Email => rows.sort_by(|a, b| a.email.cmp(&b.email)),
        }
        if order == SortOrder::Descending {
            rows.reverse();
        }
    }
    let total = i32::try_from(rows.len()).unwrap_or(i32::MAX);
    // `page` comes from the browser, so a large or negative one must not overflow.
    let start = usize::try_from(state.page.max(0).saturating_mul(PER_PAGE)).unwrap_or(0);
    (rows.into_iter().skip(start).take(PER_PAGE as usize).collect(), total)
}

fn everyone() -> Vec<User> {
    (1..=42).map(|id| User { id, email: format!("user{id}@example.com") }).collect()
}

async fn load((): (), state: TableState) -> Patches<Users> {
    let (rows, total) = query(&everyone(), &state);
    Users::users().patch(rows).and(Users::total().patch(total)).into()
}

let table = ServerTable::new(
    "Users",
    Users::table(),
    Users::users(),
    |user| user.at(User::id()),
    LOAD.call_with(Users::table()),
)
.filter("Filter emails")
.paginate(PER_PAGE, Users::total())
.sortable_column(Column::number("Id", User::id()), &By::Id)
.sortable_column(Column::text("Email", User::email()), &By::Email);

// The page renders its first rows with the same query the action runs.
let state = TableState::default().with_sorting(&By::Id, SortOrder::Ascending);
let (users, total) = query(&everyone(), &state);
let html = Page::new("Users", Users { users, total, table: state })
    .child(table)
    .render();

Next, Chart draws the rows of a list signal as lines and areas.