差分
ハンドラは差分のまとまりで応答します。中身はシグナルの新しい値、リストの変更、フラグメント、URL です。ブラウザはそれを Server-Sent Events として受け取り、順に適用します。
シグナルを設定する
Sig::patch(fn patch(self, value: T) -> SignalPatch<S>)は、ブラウザが受け取った時点でシグナルを 1 つ value に設定する差分です。SignalPatch::and(fn and(self, other: Self) -> Self)は、同じ差分にシグナルを加えます。両方にあるシグナルは other の値になります。ハンドラは SignalPatch をそのまま返すことも、into() で 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);シグナルと違う型の値を渡すと、コンパイルエラー E0308 になります。patch があるのは、パスがページの構造体から始まる Sig<S, T> だけです。リストの項目の Sig<S, T, Local> には patch がないので、サーバーはフィールドを名前で指し、リストの位置では指しません。項目をキーで変えるには リストの差分 を使います。#[signals(computed)] を付けたフィールドにも patch はありません。その値はブラウザが計算するからです。
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();フィールドの中のフィールド
at でフィールドの中のフィールドを指し、その差分はそのフィールドだけを設定します。差分が指さないシグナルは、ブラウザでそのまま残ります。Patches::all_signals(fn all_signals(self, signals: &S) -> Self)は構造体のすべてのフィールドを一度に送ります。状態を丸ごと置き換える応答に使います。
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()));イベントのまとまり
Patches::new() は空のまとまりを作り、下の各メソッドが変更を 1 つずつ加えます。ブラウザは変更を加えた順に適用します。
| メソッド | ブラウザがすること |
|---|---|
signals(patch)、all_signals(&state) | シグナルを設定する |
list(patch) | 項目を加える、置き換える、取り除く。リストの差分 を参照 |
element(&fragment) | フラグメントの id を持つ要素を置き換える。フラグメント を参照 |
navigate(url) | そのページを読み込み、あとの変更は適用しない。リンクとリダイレクト を参照 |
push_url(url)、replace_url(url) | URL を読み込まずにアドレスバーに表示する。検索パラメータ を参照 |
レスポンスの本文
axum では、ルーターがまとまりを text/event-stream の応答の本文として書きます。Patches::to_event_stream(fn to_event_stream(&self) -> String)は、axum を使わないサーバーのためにその本文を返します。文字列は最後まで送ってください。本文の末尾には応答が完結したことを示す印があり、その前で切れた応答をブラウザは失敗した呼び出しとして扱います。
型で検査しないこと
値は差分を作るときに JSON に変換されます。ブラウザが丸めてしまう -2^53 から 2^53 の範囲外の整数や、エラーを返す Serialize の実装があると patch はパニックし、ハンドラがパニックしたアクションは 500 を返します。まとまりの途中に置いた navigate のあとの変更は適用されません。push_url や replace_url の URL が画面のページのものかどうかも検査されません。
完全な例
このハンドラはメッセージをアーカイブします。1 つのまとまりで、リストからメッセージを取り除き、未読の数と状態の行を設定します。最後のテストはハンドラを呼び、value_of と removed_keys_of でまとまりを読みます。テスト用のほかのメソッドは ハンドラのテスト で説明します。
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]);