Use cases
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.
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.
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.
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.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.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.
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.
{ errors: { email?: string } }, where it only saved and redirected before."use client" and call the action through useActionState, which hands back what the action returned.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.// 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.
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.
fetch.AbortController of the request in flight, abort it when the next request starts, and ignore the AbortError the aborted one throws.searching flag in useState, set it before the request, and clear it after both a success and a failure.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.
Several features of the kinds above are added to each application below. Open one to read the change that one of those features makes.
Many visitors watch one item, and each bid changes the price on every screen.
cookies() and keep the bidder beside each open stream.leading to the state the EventSource handler merges in the Client Component, and render it.#[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.
A deploy writes its log for minutes, and the people waiting on it keep the page open.
id: line with each event, so that EventSource sends the last one back in the Last-Event-ID header when it reconnects.#[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.
Staff on the floor send orders from tablets, and a screen in the kitchen lists them.
#[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.
Visitors pick from one seat map at the same time, and two of them can pick one seat.
{ ok: false, reason: "taken" }, as the Next.js guide to error handling does for an expected error."taken". A misspelled reason is caught only where the result has a union type written for it.#[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.
Employees file expenses, and approvers work through the list of the ones waiting.
searchParams, whose values arrive as string | string[] | undefined. Parse the page number, and check the status against the ones that exist.URLSearchParams or a template string. A misspelled key builds a link that ignores the filter, with no error.// 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.
Visitors search for products as they type and filter the results, and the pages come in English and Japanese.
messages/en.json and messages/ja.json, and call t("cart.title") where the text was.[locale] segment, and pick the language for a visitor who opens /.#[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.