Computed signals
A computed signal is a field the browser keeps equal to an expression. Writing one is a compile error.
A field kept equal to an expression
Page::computed, fn computed<T, M: IsComputed>(self, signal: Sig<S, T, M>, value: impl IntoExpr<S, T>) -> Self, keeps a field equal to an expression over other fields. The browser recomputes it when a field the expression reads changes. Bindings read it like any field and run again only when its value changes, so no binding evaluates the expression itself. The field is marked #[signals(computed)] in the struct:
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>"));The server computes the value once for the first HTML, so the page shows it before the runtime loads. The value the struct holds for the field is used only where the server cannot evaluate the expression, as with one that reads Expr::now(), and the browser replaces it once the runtime has started.
An action call can pass a computed signal as an argument like any other, and Page::value_of returns its computed value in a test.
The order of computed signals
Computed signals are evaluated in the order they are declared, so one may read an earlier one and no other:
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);The types do not see the order, so Page::render, Page::value_of, and Page::simulate panic in these cases:
- A computed signal reads itself or one declared after it.
- Two
Page::computedcalls name one field. - A field marked
#[signals(computed)]is named by noPage::computedcall, since nothing would then keep it up to date. - The expression reads a list item, which has no fixed path. A total over a list is an aggregate such as
sum_ofinstead.
Writing a computed signal is a compile error
The accessor of a marked field returns a Sig<S, T, Computed>. Computed lacks the Writable trait, so the type has no set, toggle, list statement, or patch, and bind refuses it. The browser would overwrite a written value the next time a field the expression reads changes, so the write fails to compile:
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);The error notes say to write one of the signals the expression reads instead. In the other direction, Page::computed takes only a field with the mark, through the IsComputed trait, and its error names the missing attribute:
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);Computed fields of a nested struct
Sig::at takes only fields the browser may write, so a marked field of a nested struct is reached with Sig::at_computed, and only from the page root, where Page::computed can name it. A field of a list item cannot be computed: Item::at refuses a marked field, because Page::computed names one path from the page's struct.
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)));Rendering the page panics when the page reads a field reached with at_computed and no Page::computed call names it.
Functions that only read a signal
A function that only reads a signal can take a plain field and a computed one alike, as hypersig_ui::Chart does with its rows. It takes a Sig<S, T, R> with R: FromPage and calls read() on it, which gives a Sig<S, T, Read> with the same path. That type reads like the signal it came from, has no statement that writes it, and is refused by Page::computed and 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())));A view of a computed field is checked as the field is, so rendering the page still panics when the page reads it and no Page::computed call names the field.
A cart line
The total below is a computed signal over a field of a nested struct and the quantity, and the buttons change only the quantity:
Result
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: "Green tea"
.into(),
price: 4.5,
},
quantity: 1,
total: 0.0,
};
Page::new(
"Cart",
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(" at $")
.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("Total: $")
.child(span().bind_text(total.to_fixed(2))),
),
)
}Next
Signals kept across page loads keeps a field in the browser's storage for the next page.