日本語

Values that follow the signals

A binding keeps an element's text, attributes, visibility, or classes equal to an expression over the signals, in the first HTML and in the browser after each change.

An element can show a value that changes in the browser. Each binding takes an expression over the signals, such as progress.to_text() or !busy, and the runtime writes the expression's new value into the element whenever a signal it reads changes. The binding is rendered with the initial values first, so the HTML shows what the runtime would compute. Expressions covers what an expression can compute.

use hypersig::html::{button, p, span, attr};
use hypersig::{Signals, if_else};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Upload {
    progress: i32,
    busy: bool,
}

let progress = Upload::progress();
let busy = Upload::busy();

// Text that follows a signal.
let label = span::<Upload>().bind_text(progress.to_text().concat(" %"));
// An attribute that follows a signal, and one that is present while a flag is true.
let cancel = button::<Upload>()
    .bind_attr(attr::ARIA_LABEL, if_else(busy, "Cancel the upload", "Nothing to cancel"))
    .attr_when(attr::DISABLED, !busy)
    .text("Cancel");
// An element shown only while the upload runs.
let notice = p::<Upload>().show(busy).text("Uploading…");
MethodTakesKeeps in step
bind_textimpl IntoExpr<S, String>The element's text, which it replaces
bind_attrAn Attr and impl IntoExpr<S, String>The attribute's value
attr_whenAn Attr and impl IntoExpr<S, bool>Whether a boolean attribute such as disabled is present
disabledimpl IntoExpr<S, bool>disabled, as attr_when(attr::DISABLED, ...) does
showimpl IntoExpr<S, bool>Whether the element is shown
html::whenimpl IntoExpr<S, bool> and an El<S>Whether the element is in the document
class_whenA Class and impl IntoExpr<S, bool>Whether the element has the class

css_when, css_match, and bind_style do the same for the element's CSS, which Styling covers. A binding goes one way, from the signals to the element. A text field that writes back into a signal uses bind, which Binding form controls covers.

What the first HTML holds

Page::render evaluates each binding with the initial values and writes the result into the element. The upload above, rendered while nothing uploads:

use hypersig::Page;

let page = Page::new("Upload", Upload { progress: 0, busy: false })
    .child(span().bind_text(progress.to_text().concat(" %")))
    .child(
        button()
            .bind_attr(attr::ARIA_LABEL, if_else(busy, "Cancel the upload", "Nothing to cancel"))
            .attr_when(attr::DISABLED, !busy)
            .text("Cancel"),
    )
    .child(p().show(busy).text("Uploading…"));
let html = page.render();

// Each binding is evaluated with the initial values.
assert!(html.contains(">0 %</span>"));
assert!(html.contains(r#"aria-label="Nothing to cancel""#));
assert!(html.contains(r#"disabled="""#));

The HTML holds what a visitor sees before the runtime loads: the text 0 %, the label Nothing to cancel, a disabled button, and a hidden paragraph.

Text and attributes

bind_text replaces the element's text. bind_attr keeps an attribute equal to a string expression, and attr_when adds a boolean attribute such as disabled while a condition holds. Both take the attribute's name as an Attr, so they refuse the same names attr refuses, as Elements and attributes lists. A number is turned into text with to_text first, because each of them takes the type it writes, and a number where a String is expected is a compile error.

disabled(when) is attr_when(attr::DISABLED, when). The browser skips a disabled control in the tab order, ignores clicks on it, and leaves it out of a submitted form, on <button>, <input>, <select>, <textarea>, <fieldset>, <option>, and <optgroup>. Nothing checks the tag, and on another element the attribute changes nothing. A second bind_text on one element panics, because the text is one expression.

Showing and removing an element

show hides the element while a condition is false. when(cond, el) removes it instead, so each time it returns its inputs start empty and its on_load, the statement that runs when an element enters the document, runs again. show suits an element that keeps what the visitor typed while hidden, and when one that should start over.

use hypersig::html::{attr, button, div, input, p, when};
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Search {
    open: bool,
}

let open = Search::open();
let page = Page::new("Search", Search { open: false }).child(
    div()
        .child(button().on_click(open.toggle()).text("Search"))
        // Hidden while closed, and still in the document.
        .child(p().show(open).text("Type a name or an email."))
        // Out of the document while closed, so the field starts empty each time.
        .child(when(open, input().attr(attr::TYPE, "search"))),
);

when returns a Node<S>, which child takes like an element, and the first HTML holds the element only where the condition is true when the page renders. Both take a bool expression, so a signal of another type is a compile error:

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

#[derive(Signals, Serialize, Deserialize)]
struct Counter {
    count: i32,
}

// error[E0277]: `Sig<Counter, i32>` is not an expression of type `bool` on
// the page whose signals are `Counter`
let notice = p::<Counter>().show(Counter::count()).text("Counting");

A second show on one element panics, because the element has one condition: join the two with and.

Classes

class adds a static class and class_when adds one while a condition holds. Both take a Class, declared once as a const, so a misspelled class at a use site is an unknown name to the compiler. Class::new fails to compile in a const when the name is empty or holds whitespace.

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

#[derive(Signals, Serialize, Deserialize)]
struct Todo {
    done: bool,
}

// Declared once, so a misspelled class at a use site is an unknown name.
const ITEM: Class = Class::new("item");
const DONE: Class = Class::new("done");

let html = Page::new("Todo", Todo { done: true })
    .child(li().class(ITEM).class_when(DONE, Todo::done()).text("Buy milk"))
    .render();
assert!(html.contains(r#"<li class="item done""#));

A class from Class::new is not checked against any stylesheet, which suits a stylesheet the page loads from a URL, and a class that no rule selects changes nothing. A class from Stylesheet::class is checked against the CSS at compile time, as Styling shows.

Try it here

The demo binds a text field to name and shows one of two paragraphs depending on whether it is empty.

Result

greeting.rs
use hypersig::html::{div, p, span};
use hypersig::style::Style;
use hypersig::style::pattern::stack;
use hypersig::style::value::rem;
use hypersig::{Page, Signals};
use hypersig_ui::TextField;
use serde::{Deserialize, Serialize};

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

pub(super) fn page() -> Page<Greeting> {
    let name = Greeting::name();
    let typed = !name.trim().is_empty();
    Page::new(
        "Greeting",
        Greeting {
            name: String::new(),
        },
    )
    .child(
        div()
            .css(stack(rem(1)).max_width(rem(20)))
            .child(TextField::new(
                "Your name",
                name,
            ))
            .child(p().show(!&typed).text("Type your name above."))
            .child(
                p().show(typed)
                    .text("Hello, ")
                    .child(span().bind_text(name.trim()))
                    .text("!"),
            )
            .child(
                p().css(Style::new().font_size(rem(0.875)))
                    .show(name.char_count().gt(12))
                    .text("That is a long name."),
            ),
    )
}

Next, Components puts bindings like these in functions that any page can use. The signal struct covers the signals the expressions read.