Binding form controls
bind, bind_radio, and bind_select keep a form control and a signal equal in both directions.
Binding a control to a signal
El::bind, fn bind<T: Bindable, R: Writable>(self, signal: Sig<S, T, R>) -> Self, ties an <input>, a <textarea>, or a <select> to a signal in both directions. What the visitor enters is written to the signal, and a statement or a patch that changes the signal changes the control. The signal can be a field of the page or a field of a list item.
use hypersig::html::{attr, div, input, textarea};
use hypersig::{CalendarDate, Page, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Booking {
name: String,
guests: i32,
budget: Option<f64>,
arrival: CalendarDate,
newsletter: bool,
notes: String,
}
let form = div::<Booking>()
.child(input().bind(Booking::name()))
.child(input().attr(attr::TYPE, "number").bind(Booking::guests()))
.child(input().attr(attr::TYPE, "number").bind(Booking::budget()))
.child(input().attr(attr::TYPE, "date").bind(Booking::arrival()))
.child(input().attr(attr::TYPE, "checkbox").bind(Booking::newsletter()))
.child(textarea().bind(Booking::notes()));render writes each initial value into its control: the value of a text, number, or date field, the text of a <textarea>, and checked for a checkbox. A None writes no value, so the field starts empty.
The types a control binds to
T must implement Bindable, which is sealed. The type decides how the runtime reads the control's text and when it writes the signal:
| Type | Control | Writes the signal on |
|---|---|---|
String | text field, <textarea>, <select> | each input |
bool | checkbox, as checked | change |
i32, i64 | number or range field | each edit |
f64 | number or range field | each edit |
CalendarDate | date field | each edit |
Option of String, i32, i64, f64, or CalendarDate | as the type it holds | as the type it holds |
- An
Optionstands for an empty field in both directions:Noneempties the field, and emptying the field setsNone. - A number field whose text is not a number, and a date field whose text is not a
YYYY-MM-DDdate, leave the signal as it was. An emptied field bound to a plain number or date leaves it as it was too, because the type holds no empty value. binddoes not set thetypeattribute. A checkbox needsattr(attr::TYPE, "checkbox"), and a number or date field its owntype, as the sample sets them.
Any other type is a compile error that names the types bind takes. An enum goes to radio buttons or a <select>, through the two methods below. A u64 and an Option<bool> are refused the same way, the second because a checkbox has no empty state to stand for None:
use hypersig::html::input;
use hypersig::Signals;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq)]
enum Sort {
Newest,
Cheapest,
}
#[derive(Signals, Serialize, Deserialize)]
struct Catalog {
sort: Sort,
}
// error[E0277]: a form control cannot be bound to a `Sort` signal
let field = input::<Catalog>().bind(Catalog::sort());Radio buttons
El::bind_radio, fn bind_radio<T: Serialize + PartialEq, R: Writable>(self, signal: Sig<S, T, R>, value: &T) -> Self, makes an <input> a radio button that sets signal to value when the visitor checks it, and that is checked while signal equals value. It sets type="radio" itself, and T can be any serializable type, such as an enum:
use hypersig::html::{div, input, label};
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq)]
enum Shipping {
Standard,
Express,
}
#[derive(Signals, Serialize, Deserialize)]
struct Checkout {
shipping: Shipping,
}
let shipping = Checkout::shipping();
let choice = div::<Checkout>()
.child(label().child(input().bind_radio(shipping, &Shipping::Standard)).text("Standard"))
.child(label().child(input().bind_radio(shipping, &Shipping::Express)).text("Express"));A select of values
El::bind_select, fn bind_select<T: Serialize + PartialEq, R: Writable, L: Into<String>>(self, signal: Sig<S, T, R>, options: impl IntoIterator<Item = (T, L)>) -> Self, fills a <select> with one <option> per value and label and binds it to signal. The option equal to the signal starts selected, and a choice writes its value to the signal on change:
use hypersig::html::select;
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq)]
enum Sort {
Newest,
Cheapest,
}
#[derive(Signals, Serialize, Deserialize)]
struct Catalog {
sort: Sort,
}
let picker = select::<Catalog>().bind_select(
Catalog::sort(),
[(Sort::Newest, "Newest first"), (Sort::Cheapest, "Lowest price")],
);What panics when the page is built
The element type is not part of El<S>, so these mistakes compile and panic when the element is built:
bindon an element other than<input>,<textarea>, and<select>,bind_radioon one other than<input>, andbind_selecton one other than<select>.- A second binding on one control, by any of the three methods, and
bind_radioon an<input>already given atype. - A radio or option value that fails to serialize, or that holds an integer outside -2^53 to 2^53.
Line breaks
The browser shows each line break of a <textarea> as \n, and an <input> drops line breaks. A signal that holds \r\n for a textarea, or a line break for an input, keeps it until the visitor edits the field, so its length differs from what the field shows, and an untouched field sends it back as it came. Text saved by a plain HTML form holds \r\n, because a browser submits a textarea's line breaks so. Replace \r\n with \n where the text enters the page's signals to keep the two the same.
While the visitor is typing
An action's answer can send back text the visitor typed before typing on, as when an autosave sends each pause. While the field has focus, such an answer leaves the field as the visitor has it and puts the field's text back in the signal, so the next call sends what the visitor sees. Any other value shows at once and keeps the caret, so a statement that empties the field after Enter, or picks a suggestion, takes effect while the visitor is still in the field.
Signals a control cannot write
The three methods take R: Writable, so a computed signal and a read-only view from read() are compile errors, which Computed signals shows. A checkbox that only shows a derived state, such as "all done", uses bind_checked, a one-way binding that Values that follow the signals covers.
A coffee order
Each control of the order writes one field, and the total is an expression over two of them:
use hypersig::html::{attr, form, input, label, p, select, span};
use hypersig::{NumberFormat, Page, Signals, if_else};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq)]
enum Size {
Small,
Large,
}
#[derive(Serialize, Deserialize, PartialEq)]
enum Milk {
None,
Oat,
Whole,
}
#[derive(Signals, Serialize, Deserialize)]
struct Coffee {
size: Size,
milk: Milk,
shots: i32,
to_go: bool,
name: Option<String>,
}
const PRICE: NumberFormat = NumberFormat::new().digits(2).prefix("$");
let size = Coffee::size();
let shots = Coffee::shots();
let base = if_else(size.equals(&Size::Large), 4.0, 3.0);
let price = base + shots.to_f64() * 0.75;
let order = Page::new(
"Coffee",
Coffee { size: Size::Small, milk: Milk::None, shots: 1, to_go: false, name: None },
)
.child(
form()
.child(label().child(input().bind_radio(size, &Size::Small)).text("Small"))
.child(label().child(input().bind_radio(size, &Size::Large)).text("Large"))
.child(select().bind_select(
Coffee::milk(),
[(Milk::None, "No milk"), (Milk::Oat, "Oat milk"), (Milk::Whole, "Whole milk")],
))
.child(
label()
.text("Shots")
.child(input().attr(attr::TYPE, "number").attr(attr::MIN, "1").bind(shots)),
)
.child(
label()
.child(input().attr(attr::TYPE, "checkbox").bind(Coffee::to_go()))
.text("To go"),
)
.child(label().text("Name for the cup").child(input().bind(Coffee::name())))
.child(p().text("Total: ").child(span().bind_text(price.format(&PRICE)))),
);Next
Computed signals keeps a field equal to an expression, such as that total. Forms sends a form to the server and shows its validation errors.