English

計算シグナル

計算シグナルは、ブラウザが式の値に保ち続けるフィールドです。書き込もうとするとコンパイルエラーになります。

式の値に保たれるフィールド

Page::computed(fn computed<T, M: IsComputed>(self, signal: Sig<S, T, M>, value: impl IntoExpr<S, T>) -> Self)は、フィールドをほかのフィールドを使った式の値に保ち続けます。式が読むフィールドが変わると、ブラウザが計算し直します。束縛はそれぞれ式を評価する代わりに、ほかのフィールドと同じようにこの値を読み、値が変わったときだけ評価し直します。構造体ではそのフィールドに #[signals(computed)] を付けます。

use hypersig::html::span;
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Cart {
    price: f64,
    quantity: i32,
    // The value given here reaches the page only where the server cannot
    // evaluate the expression.
    #[signals(computed)]
    total: f64,
}

let html = Page::new("Cart", Cart { price: 2.5, quantity: 3, total: 0.0 })
    .computed(Cart::total(), Cart::price() * Cart::quantity().to_f64())
    .child(span().bind_text(Cart::total().to_text()))
    .render();
assert!(html.contains(">7.5</span>"));

サーバーは最初の HTML のために値を一度計算するので、ページはランタイムを読み込む前からその値を表示します。構造体がそのフィールドに持たせた値が使われるのは、Expr::now() を読む式のようにサーバーが評価できない場合だけで、その値もランタイムの起動後にブラウザが置き換えます。

アクションの呼び出しはほかのシグナルと同じように計算シグナルを引数として渡せます。テストでは、Page::value_of が計算された値を返します。

計算シグナルの順序

計算シグナルは宣言した順に評価されるので、先に宣言したものだけを読めます。

use hypersig::html::{p, span};
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Invoice {
    hours: f64,
    rate: f64,
    #[signals(computed)]
    net: f64,
    #[signals(computed)]
    tax: f64,
    #[signals(computed)]
    gross: f64,
}

let net = Invoice::net();
let tax = Invoice::tax();

// Each one reads only the ones declared above it.
let page = Page::new("Invoice", Invoice { hours: 10.0, rate: 80.0, net: 0.0, tax: 0.0, gross: 0.0 })
    .computed(net, Invoice::hours() * Invoice::rate())
    .computed(tax, net * 0.1)
    .computed(Invoice::gross(), net + tax)
    .child(p().text("Total: ").child(span().bind_text(Invoice::gross().to_fixed(2))));
assert_eq!(page.value_of(Invoice::gross()), 880.0);

この順序は型には見えないので、次の場合には Page::render、Page::value_of、Page::simulate が panic します。

  • 計算シグナルが自分自身か、後に宣言したものを読むとき。
  • 2 つの Page::computed の呼び出しが同じフィールドを指すとき。
  • #[signals(computed)] を付けたフィールドを、どの Page::computed の呼び出しも指していないとき。値を最新に保つものがなくなるからです。
  • 式がリストの項目を読むとき。項目には固定したパスがないからです。リスト全体の合計には代わりに sum_of のような集計を使います。

計算シグナルへの書き込みはコンパイルエラーになる

印を付けたフィールドのアクセサーは Sig<S, T, Computed> を返します。Computed は Writable トレイトを実装していないので、この型には set、toggle、リストの文、patch がなく、bind にも渡せません。書き込んだ値は、式が読むフィールドが次に変わったときにブラウザが上書きするので、書き込みはコンパイルが通りません。

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

#[derive(Signals, Serialize, Deserialize)]
struct Cart {
    price: f64,
    #[signals(computed)]
    total: f64,
}

// error[E0599]: the method `set` exists for struct `Sig<Cart, f64, Computed>`, but its trait bounds were not satisfied
let reset = Cart::total().set(0.0);

エラーの注記には、代わりに式が読むシグナルのどれかに書き込むよう示されます。逆に、Page::computed は IsComputed トレイトを通して印の付いたフィールドだけを受け取り、そのエラーは足りない属性を示します。

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

#[derive(Signals, Serialize, Deserialize)]
struct Cart {
    price: f64,
    total: f64,
}

// error[E0277]: `Page::computed` takes a field marked `#[signals(computed)]`
let page = Page::new("Cart", Cart { price: 2.5, total: 0.0 })
    .computed(Cart::total(), Cart::price() * 2.0);

入れ子の構造体にある計算フィールド

Sig::at はブラウザが書き込めるフィールドしか受け取らないので、入れ子の構造体にある印の付いたフィールドには Sig::at_computed でたどり着きます。これはページのルートからだけ使え、そこでは Page::computed がそのフィールドを指せます。リスト項目のフィールドは計算シグナルにできません。Page::computed が指すのはページの構造体からの 1 つのパスなので、Item::at は印の付いたフィールドを拒否します。

use hypersig::html::span;
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Totals {
    net: f64,
    #[signals(computed)]
    gross: f64,
}

#[derive(Signals, Serialize, Deserialize)]
struct Invoice {
    totals: Totals,
}

let totals = Invoice::totals();
// `at` refuses a computed field, and `at_computed` takes one.
let gross = totals.at_computed(Totals::gross());

let page = Page::new("Invoice", Invoice { totals: Totals { net: 100.0, gross: 0.0 } })
    .computed(gross, totals.at(Totals::net()) * 1.1)
    .child(span().bind_text(gross.to_fixed(2)));

at_computed でたどったフィールドをページが読むのに、どの Page::computed の呼び出しもそれを指していなければ、ページの描画が panic します。

シグナルを読むだけの関数

シグナルを読むだけの関数は印のないフィールドと計算フィールドのどちらも受け取れます。hypersig_ui::Chart は行をこの方法で受け取ります。R: FromPage の Sig<S, T, R> を受け取って read() を呼ぶと、同じパスを持つ Sig<S, T, Read> が得られます。この型でも値は元のシグナルと同じように読めますが、書き込む文はなく、Page::computed と Page::persist にも渡せません。

use hypersig::html::{El, div, span};
use hypersig::{FromPage, Page, Read, Sig, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Cart {
    price: f64,
    quantity: i32,
    #[signals(computed)]
    total: f64,
}

// Takes a plain field and a computed one alike, and cannot write either.
fn amount<S, R: FromPage>(value: Sig<S, f64, R>) -> El<S> {
    let value: Sig<S, f64, Read> = value.read();
    span().bind_text(value.to_fixed(2))
}

let page = Page::new("Cart", Cart { price: 2.5, quantity: 3, total: 0.0 })
    .computed(Cart::total(), Cart::price() * Cart::quantity().to_f64())
    .child(div().child(amount(Cart::price())).child(amount(Cart::total())));

計算フィールドから作ったビューも元のフィールドと同じように検査されるので、ページがそれを読むのに、どの Page::computed の呼び出しもそのフィールドを指していなければ、ページの描画が panic します。

カートの 1 行

下の合計は入れ子の構造体のフィールドと数量から作る計算シグナルで、ボタンは数量だけを変えます。

実行結果

cart.rs
use hypersig::html::{div, p, span, attr};
use hypersig::style::pattern::{hstack, stack};
use hypersig::style::value::rem;
use hypersig::{Page, Signals};
use hypersig_ui::{ButtonSize, ButtonVariant, button};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Item {
    name: String,
    price: f64,
}

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Cart {
    item: Item,
    quantity: i32,
    #[signals(computed)]
    total: f64,
}

pub(super) fn page() -> Page<Cart> {
    let item = Cart::item();
    let quantity = Cart::quantity();
    let total = Cart::total();
    let initial = Cart {
        item: Item {
            name: "緑茶"
                .into(),
            price: 4.5,
        },
        quantity: 1,
        total: 0.0,
    };
    Page::new(
        "カート",
        initial,
    )
    .computed(total, item.at(Item::price()) * quantity.to_f64())
    .child(
        div()
            .css(stack(rem(0.75)))
            .child(
                p().child(span().bind_text(item.at(Item::name())))
                    .text("、単価 $")
                    .child(span().bind_text(item.at(Item::price()).to_fixed(2))),
            )
            .child(
                div()
                    .css(hstack(rem(0.75)))
                    .child(
                        button(ButtonVariant::Outline, ButtonSize::Sm)
                            .attr_when(attr::DISABLED, quantity.le(1))
                            .on_click(quantity.set(quantity - 1))
                            .text("-"),
                    )
                    .child(span().bind_text(quantity.to_text()))
                    .child(
                        button(ButtonVariant::Outline, ButtonSize::Sm)
                            .on_click(quantity.set(quantity + 1))
                            .text("+"),
                    ),
            )
            .child(
                p().text("合計 $")
                .child(span().bind_text(total.to_fixed(2))),
            ),
    )
}

次に読むページ

ページをまたいで保つシグナル ではフィールドをブラウザのストレージに保存して次のページに引き継ぎます。