日本語

Patches

A handler answers with a batch of patches: new values for signals, list changes, fragments, and URLs. The browser receives them as Server-Sent Events and applies them in order.

Setting a signal

Sig::patch, fn patch(self, value: T) -> SignalPatch<S>, sets one signal to value once the browser receives it. SignalPatch::and, fn and(self, other: Self) -> Self, adds more signals to the same patch, and a signal present in both takes other's value. A handler can return the SignalPatch itself, or convert it with into() into a Patches<S>.

use hypersig::{Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Inbox {
    unread: i32,
    status: String,
}

// One signal, as a handler's whole answer.
let one: Patches<Inbox> = Inbox::unread().patch(0).into();

// Several signals in one event.
let both: Patches<Inbox> = Inbox::unread()
    .patch(3)
    .and(Inbox::status().patch("3 new messages".to_owned()))
    .into();

assert_eq!(both.value_of(Inbox::unread()), Some(3));
assert_eq!(one.value_of(Inbox::status()), None);

A value of another type than the signal's is a compile error, E0308. patch exists only on a Sig<S, T>, whose path starts at the page's struct. The Sig<S, T, Local> of a list item has no patch, so the server addresses fields by name and never by a list position: List patches changes items by key. A field marked #[signals(computed)] has no patch either, because the browser computes it.

use hypersig::{Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Inbox {
    unread: i32,
}

// error[E0308]: mismatched types: expected `i32`, found `String`
let patches: Patches<Inbox> = Inbox::unread().patch("3 new".to_owned()).into();

Fields inside fields

at reaches a field inside a field, and a patch of it sets that field alone: the browser leaves every signal the patch does not name as it was. Patches::all_signals, fn all_signals(self, signals: &S) -> Self, sends every field of the struct at once, for an answer that replaces the whole state.

use hypersig::{Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Address {
    city: String,
    zip: String,
}

#[derive(Signals, Serialize, Deserialize)]
struct Account {
    name: String,
    address: Address,
}

// A field inside a field, set on its own: `zip` and `name` keep their values.
let city: Patches<Account> = Account::address()
    .at(Address::city())
    .patch("Kyoto".to_owned())
    .into();
assert_eq!(city.value_of(Account::address().at(Address::city())), Some("Kyoto".to_owned()));
assert_eq!(city.value_of(Account::name()), None);

// `all_signals` sends every field of the struct.
let account = Account {
    name: "Ada".to_owned(),
    address: Address { city: "Kyoto".to_owned(), zip: "600-8216".to_owned() },
};
let all = Patches::new().all_signals(&account);
assert_eq!(all.value_of(Account::name()), Some("Ada".to_owned()));

A batch of events

Patches::new() starts an empty batch, and each method below adds one change to it. The browser applies the changes in the order they were added.

MethodWhat the browser does
signals(patch), all_signals(&state)Sets the signals
list(patch)Adds, replaces, or removes items, as List patches shows
element(&fragment)Replaces the element with the fragment's id, as Fragments shows
navigate(url)Loads that page, and applies none of the changes after it, as Links and redirects shows
push_url(url), replace_url(url)Shows the URL in the address bar without loading it, as Search parameters shows

The response body

With axum, the router writes the batch as the body of a text/event-stream answer. Patches::to_event_stream, fn to_event_stream(&self) -> String, returns that body for a server that does not use axum. Send the whole string: the body ends with a mark that the answer is complete, and the browser counts an answer cut off before it as a failed call.

What the types leave unchecked

A value is converted to JSON when the patch is built. An integer outside -2^53 to 2^53, which the browser would round, or a Serialize impl that returns an error, makes patch panic, and an action whose handler panics answers 500. A navigate in the middle of a batch leaves the changes after it unapplied, and nothing checks that the URL of push_url or replace_url belongs to the page on screen.

A complete example

This handler archives a message: one batch removes the message from the list and sets the unread count and the status line. The test at the end calls the handler and reads the batch with value_of and removed_keys_of, which Testing handlers covers with the rest of the methods for tests.

use std::sync::{Arc, Mutex};

use hypersig::html::{button, each_keyed, li, p, span, ul};
use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};

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

#[derive(Signals, Serialize, Deserialize)]
struct Inbox {
    messages: Vec<Message>,
    unread: i32,
    status: String,
}

#[derive(Clone, Default)]
struct Store(Arc<Mutex<Vec<Message>>>);

hypersig::routes! {
    fn pages(Router<Store>);
    action ARCHIVE: Action<Inbox, i32> = post "/archive" => archive;
}

// One answer removes the message and sets two signals.
async fn archive(store: Store, id: i32) -> Patches<Inbox> {
    let mut messages = store.0.lock().expect("no handler panics while it holds the store");
    messages.retain(|message| message.id != id);
    let left = i32::try_from(messages.len()).unwrap_or(i32::MAX);
    Patches::new()
        .list(Inbox::messages().patch_remove(&[id], |message| message.at(Message::id())))
        .signals(
            Inbox::unread()
                .patch(left)
                .and(Inbox::status().patch(format!("{left} left"))),
        )
}

let page = ul::<Inbox>()
    .child(each_keyed(
        Inbox::messages(),
        |message| message.at(Message::id()),
        |message| {
            li().child(span().bind_text(message.at(Message::subject())))
                .child(button().on_click(ARCHIVE.call_with(message.at(Message::id()))).text("Archive"))
        },
    ))
    .child(p().bind_text(Inbox::status()));

let store = Store::default();
store.0.lock().unwrap().push(Message { id: 7, subject: "Hello".to_owned() });
let patches = archive(store, 7).await;
assert_eq!(patches.value_of(Inbox::unread()), Some(0));
assert_eq!(patches.value_of(Inbox::status()), Some("0 left".to_owned()));
assert_eq!(patches.removed_keys_of(Inbox::messages(), |message| message.at(Message::id())), [7]);

Next, List patches sends only the items of a list that change, and Fragments sends HTML for a part of the page.