日本語

Use cases

What one more feature changes in the code

A screen built with hypersig can look and behave like one built with Next.js. The difference is in which files change and what has to be written by hand when one more feature is added. Each hypersig change below is code that cargo test compiles, beside the work the same feature takes in Next.js 16 with the App Router.

Where the difference comes from

The features on this page fall into three kinds, by what the framework handles for them. The Next.js work starts from the shape of the TodoMVC in bench/compare/next, where a Server Component reads the data and a Client Component holds it in useState. In each hypersig change, a green line was added and a red line removed.

AA change made on the server reaches every open tab

Another visitor's write, a job's progress, or a deadline changes the screen while the visitor does nothing. A Server Action answers only the tab that called it, so in Next.js these changes need a second path: a stream of their own, and client code that merges what arrives into the state. In hypersig, a stream sends the same Patches an action answers with, and the runtime applies both the same way. Streams covers them.

Show the tasks other people add, without a reload.

In Next.js 16 with the App Router

  • Add a Route Handler such as app/api/tasks/stream/route.ts that returns a ReadableStream with the text/event-stream content type. Keep the open streams in a list, and write to each of them after a Server Action saves a task.
  • In the Client Component, open an EventSource in useEffect, read each event with JSON.parse, and put the result into useState. JSON.parse returns any, so the shape of what arrives is not checked.
  • EventSource reconnects by itself, and the changes made while it was away are lost unless the handler sends them again, from the Last-Event-ID header or from a fresh read of the list.

In hypersig

use futures::{Stream, StreamExt as _, stream};use hypersig::html::{div, each, li, ul};use hypersig::{Action, Page, Patches, Signals, StreamAction};use serde::{Deserialize, Serialize};use tokio::sync::broadcast; hypersig::routes! {    fn pages(Router<AppState>);    action ADD: Action<Board, String> = post "/tasks" => add;    stream UPDATES: StreamAction<Board> = "/tasks/updates" => updates;} let page = Page::new("Board", Board { tasks: Vec::new() }).child(    div()        .on_load(UPDATES.call().reconnect())        .child(ul().child(each(Board::tasks(), |task| li().bind_text(task.at(Task::title()))))),); async fn add(state: AppState, title: String) -> Patches<Board> {    let tasks = state.add(title);    Board::tasks().patch(tasks).into()    let _ = state.changed.send(tasks);    Patches::new()} // Each open tab holds one stream. It sends the list as it is now, which a// tab that reconnects needs, then the list after each write.fn updates(state: AppState, (): ()) -> impl Stream<Item = Patches<Board>> {    let now = state.list();    let changes = stream::unfold(state.changed.subscribe(), |mut changes| async move {        let tasks = changes.recv().await.ok()?;        Some((tasks, changes))    });    stream::iter([now]).chain(changes).map(|tasks| Board::tasks().patch(tasks).into())} let (changed, _) = broadcast::channel(16);let _app: Router = pages(Router::new()).with_state(AppState { changed });

The list arrives as a typed patch of Board::tasks(). Every connection, a reconnection included, starts with the list as it is now.

BThe browser and the server use one name from a Rust type

A message the server reports under a field, a filter kept in the URL, the status of a failed request, and a translated text each work only while the browser and the server agree on a name. In Next.js, a query key and a translation key are strings, and an error from a Server Action reaches the page through a Client Component that holds the action's state. In hypersig, the name comes from a Rust item that both sides read, so a name that does not match fails to compile. The item is a field of a Signals struct, a Search struct, a StatusCode, or a field of the translation struct. Forms covers the rules both sides check.

If the email address is already registered, say so under the email field.

In Next.js 16 with the App Router

  • Make the Server Action return the errors, as in { errors: { email?: string } }, where it only saved and redirected before.
  • Mark the form "use client" and call the action through useActionState, which hands back what the action returned.
  • Render state.errors?.email under the field. Where a library checks the field in the browser, its message lives in another state, and showing both in one place takes code written by hand.

In hypersig

// Under the field, the message the browser's rules write..child(span().bind_text(signup.error(email))) async fn join(state: AppState, value: Signup) -> Patches<Join> {    let signup = Join::signup();    if let Err(errors) = Form::validate(&value) {        return signup.reject(&errors).into();    }    if state.is_taken(&value.email) {        let taken = FieldErrors::new().add(Signup::email(), "That address is taken.");        return signup.reject(&taken).into();    }    signup.patch(Form::new(Signup::default())).into()}

The browser's rule and the server's check both write into signup.error(email), which the page already shows.

CThe runtime orders the requests and handles their failures

A slow answer arrives after a newer one, the connection drops, or the visitor presses the button again while it waits. In Next.js, the component handles these with an AbortController, a pending flag, and code that reconnects. In hypersig, each is a method on the call: .latest() aborts the earlier call, .indicator() sets a flag while the call waits, and .reconnect() opens a stream again. Calls that overlap covers .latest(), Busy and failed calls covers .indicator(), and Streams covers .reconnect().

Search as the visitor types, show that it is searching, and never let an older result replace a newer one.

In Next.js 16 with the App Router

  • Move the search box into a Client Component, and from the input's change handler, after a timer for the debounce, call a Route Handler with fetch.
  • Keep the AbortController of the request in flight, abort it when the next request starts, and ignore the AbortError the aborted one throws.
  • Keep a searching flag in useState, set it before the request, and clear it after both a success and a failure.

In hypersig

let _ = div()    .child(input().bind(query).on_debounced(        Event::Input,        Duration::from_millis(200),        FIND.call_with(query),        FIND.call_with(query).indicator(Search::searching()).latest(),    ))    .child(p().show(Search::searching()).text("Searching…"));

.latest() aborts the call still waiting, and drops those of its patches that had not arrived yet.

Applications these features are added to

Several features of the kinds above are added to each application below. Open one to read the change that one of those features makes.

Auction

Many visitors watch one item, and each bid changes the price on every screen.

AServer pushesBOne nameCOrder and failure
  • AShow each bid on every open screen as it is placed.
  • ATell each bidder whether they hold the highest bid.
  • BRefuse a bid placed after the close, with the reason under the bid field.
  • CKeep the bid button disabled while a bid is being sent.

In Next.js 16 with the App Router

  • In the stream's Route Handler, read the session with cookies() and keep the bidder beside each open stream.
  • For each bid, write a different event to each stream, by comparing the bid's bidder with the stream's.
  • Add leading to the state the EventSource handler merges in the Client Component, and render it.

In hypersig

#[derive(Signals, Serialize, Deserialize)]struct Auction {    price: i32,    leading: bool,} div()    .on_load(BIDS.call().reconnect())    .child(span().bind_text(Auction::price().to_text()))    .child(p().show(Auction::leading()).text("You are the highest bidder.")) // The stream knows whose tab it serves, so each tab receives its own answer.fn bids(state: AppState, (): ()) -> impl Stream<Item = Patches<Auction>> {fn bids(state: AppState, Member(me): Member, (): ()) -> impl Stream<Item = Patches<Auction>> {    futures::stream::unfold(state.bids.subscribe(), move |mut bids| {        let me = me.clone();        async move {            let bid = bids.recv().await.ok()?;            let price = Auction::price().patch(bid.amount);            Some((price.into(), bids))            let leading = Auction::leading().patch(bid.bidder == me);            Some((price.and(leading).into(), bids))        }    })}

A stream's handler takes an extractor as an action's does, so the stream of each tab compares the bid with its own member.

Deploy progress

A deploy writes its log for minutes, and the people waiting on it keep the page open.

AServer pushesBOne nameCOrder and failure
  • AStream each log line as the deploy writes it.
  • CAfter the connection drops, continue from the next line without repeating a line.
  • BWhen the session has expired, show a link to sign in again in place of the error.

In Next.js 16 with the App Router

  • Write an id: line with each event, so that EventSource sends the last one back in the Last-Event-ID header when it reconnects.
  • Read that header in the Route Handler, and start the log after the line it names.

In hypersig

#[derive(Signals, Serialize, Deserialize)]struct Deploy {    lines: Vec<Line>,    last: i32,} hypersig::routes! {    fn pages(Router<AppState>);    stream LOG: StreamAction<Deploy> = "/deploy/log" => log;    stream LOG: StreamAction<Deploy, i32> = "/deploy/log" => log;}     .on_load(LOG.call().reconnect())    // Each reconnection sends the id of the last line on screen.    .on_load(LOG.call_with(Deploy::last()).reconnect())    .child(ol().child(each(Deploy::lines(), |line| li().bind_text(line.at(Line::text()))))); fn log(state: AppState, (): ()) -> impl Stream<Item = Patches<Deploy>> {    stream::unfold(0, move |after| {fn log(state: AppState, last: i32) -> impl Stream<Item = Patches<Deploy>> {    stream::unfold(last, move |after| {        let state = state.clone();        async move {            let lines = state.lines_after(after).await;            let next = lines.last().map_or(after, |line| line.id);            Some((Deploy::lines().patch_append(&lines).into(), next))            let patches = Patches::new()                .list(Deploy::lines().patch_append(&lines))                .signals(Deploy::last().patch(next));            Some((patches, next))        }    })}

The id of the last line is a signal the stream's patches keep up to date, and each reconnection sends it as the stream's argument. A response the host closes before the stream ends, as a host does at its time limit, also counts as broken off, and the runtime opens it again.

Restaurant orders

Staff on the floor send orders from tablets, and a screen in the kitchen lists them.

AServer pushesBOne name
  • AShow an order on the kitchen screen as soon as it is sent.
  • BIf a dish is sold out, say so on that line of the order.

In Next.js 16 with the App Router

  • Make the Server Action return which line failed and why. The Next.js guide to error handling models an expected error as a returned value, and leaves thrown errors to error boundaries.
  • Keep a map from a line's id to its message in the Client Component's state, set an entry on a failure, and remove it on a success.
  • Read each line's message from that map where the line renders.

In hypersig

#[derive(Signals, Serialize, Deserialize)]struct Line {    id: i32,    dish: String,    problem: String,} each(Order::lines(), |line| {    li().child(span().bind_text(line.at(Line::dish())))        .child(button().text("Send to the kitchen").on_click(            SEND.call_with(line.at(Line::id())),            SEND.call_with(line.at(Line::id()))                // The failure lands on the line whose button was pressed.                .on_error(|message| line.at(Line::problem()).set(message))                .on_success(line.at(Line::problem()).set("")),        ))        .child(span().bind_text(line.at(Line::problem())))}) async fn send(state: AppState, line: i32) -> Result<Patches<Order>, (StatusCode, &'static str)> {    if state.sold_out(line) {        return Err((StatusCode::CONFLICT, "Sold out. Ask the guest for another dish."));    }    Ok(Patches::new())}

.on_error runs where the call was made, so inside each it reaches the line whose button was pressed.

Seat booking

Visitors pick from one seat map at the same time, and two of them can pick one seat.

AServer pushesBOne name
  • AMark a seat as taken on every screen once someone holds it.
  • BIf someone else took the seat a moment ago, tell the visitor so.

In Next.js 16 with the App Router

  • Return a value that tells the outcomes apart from the Server Action, such as { ok: false, reason: "taken" }, as the Next.js guide to error handling does for an expected error.
  • Compare the reason in the Client Component and render the message for "taken". A misspelled reason is caught only where the result has a union type written for it.

In hypersig

#[derive(Signals, Serialize, Deserialize)]struct Booking {    seat: String,    failure: i32,} let taken = i32::from(StatusCode::CONFLICT.as_u16());let _ = div()    .child(button().on_click(HOLD.call_with(Booking::seat())).text("Hold this seat"))    .child(button().on_click(HOLD.call_with(Booking::seat()).status(Booking::failure())).text("Hold this seat"))    .child(p().show(Booking::failure().equals(taken)).text("Someone took this seat a moment ago. Pick another.")); async fn hold(state: AppState, seat: String) -> Result<Patches<Booking>, StatusCode> {    if !state.hold(&seat) {        return Err(StatusCode::CONFLICT);    }    Ok(Patches::new())}

The status of the failed answer goes into a signal, and the page compares it with StatusCode::CONFLICT, the status the handler returns.

Expense approvals

Employees file expenses, and approvers work through the list of the ones waiting.

AServer pushesBOne name
  • AWhen an expense is approved, change its status on the screen of the person who filed it.
  • BCheck the budget on the server, and show an overrun under the amount field.
  • BKeep the list's filter in the URL, so a link to it can be shared.

In Next.js 16 with the App Router

  • Read the filter from the page's searchParams, whose values arrive as string | string[] | undefined. Parse the page number, and check the status against the ones that exist.
  • Build each link's query with URLSearchParams or a template string. A misspelled key builds a link that ignores the filter, with no error.

In hypersig

// Both fields are `Option`, so `/requests` without a query string still loads.#[derive(Signals, Search, Serialize, Deserialize)]struct Filter {    status: Option<String>,    page: Option<i32>,} hypersig::routes! {    fn pages(Router<()>);    const REQUESTS: Route = "/requests" => requests;    // `requests` receives the filter as a `Filter`.    const REQUESTS: Route<(), Filter> = "/requests" => requests;} let waiting = Filter { status: Some("waiting".to_owned()), page: None };let link = a::<Requests>().href(REQUESTS.link());let link = a::<Requests>().href(REQUESTS.link_with(&waiting));assert_eq!(link.render(), r#"<a href="/requests?status=waiting"></a>"#);

The handler receives a Filter, and a link passes one. A field that is None stays out of the link, and a missing key arrives as None, so the bare /requests loads where a required field would get a 400. Route::link exists only on a route without parameters, so once the route takes a filter, each link that passes none fails to compile.

An online shop in two languages

Visitors search for products as they type and filter the results, and the pages come in English and Japanese.

BOne nameCOrder and failure
  • CSearch as the visitor types, and never show an older result over a newer one.
  • BKeep the filters in the URL.
  • BAdd an English version of each page.

In Next.js 16 with the App Router

  • With a library such as next-intl, move each text to a key in messages/en.json and messages/ja.json, and call t("cart.title") where the text was.
  • Put the pages under a [locale] segment, and pick the language for a visitor who opens /.
  • Unless the project's types check every language's file, a key missing from one file is not a type error, and shows up as a missing text at run time.

In hypersig

#[derive(Segment, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]#[serde(rename_all = "lowercase")]enum Lang {    En,    Ja,} hypersig::routes! {    fn pages(Router<()>);    const CART: Route = "/cart" => cart;    const CART: Route<Lang> = "/{lang}/cart" => cart;} async fn cart((): (), (): ()) -> Page<Cart> {    Page::new("ご注文内容", Cart {}).child(p().text("送料は無料です。"))async fn cart((): (), lang: Lang) -> Page<Cart> {    let title = lang.pick(ByLang { en: "Your order", ja: "ご注文内容" });    let shipping = lang.pick(ByLang { en: "Shipping is free.", ja: "送料は無料です。" });    Page::new(title, Cart {}).child(p().text(shipping))}

A text holds its translations in one struct, so a text without its English fails to compile, and a language added to Lang fails to compile until every text has it. i18n covers the crate.