日本語

Timers and reactions

Statements that run on a timer, when an element is added to the document, or when a signal changes, and the browser's clock and random numbers that they can read.

Five ways to run a statement

Each method below is on El<S> and takes a statement, a Stmt<S> or anything that turns into one. The statement runs in the browser at the time the table gives, with no click or keystroke.

MethodWhen the statement runs
on_interval(period: Duration, stmt)Every period while the element is in the document
on_timeout(delay: Duration, stmt)Once, delay after the element is added to the document, unless the element has been removed by then
on_load(stmt)Once, when the element is added to the document
effect(stmt)When the element is added, and again whenever a signal the statement reads changes
on_signal_change(signal: Sig<S, T, R>, stmt)Whenever the signal, or any field inside it, changes, whatever changed it

Intervals and timeouts

on_interval and on_timeout take a std::time::Duration. One element holds one interval and one timeout: a second call of either replaces the first.

use std::time::Duration;

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

#[derive(Signals, Serialize, Deserialize)]
struct Clock {
    running: bool,
    tenths: i32,
    hint: bool,
}

let (running, tenths, hint) = (Clock::running(), Clock::tenths(), Clock::hint());
let signals = Clock { running: true, tenths: 0, hint: false };
let page = Page::new("Clock", signals).child(
    div()
        // Every 100 milliseconds while the element is in the document.
        .on_interval(Duration::from_millis(100), Stmt::when(running, tenths.set(tenths + 1)))
        // Once, 3 seconds after the element is added.
        .on_timeout(Duration::from_secs(3), hint.set(true))
        .child(span().bind_text(tenths.to_text()))
        .child(p().show(hint).text("Tenths of a second since the page loaded")),
);

The interval runs every 100 milliseconds, and its statement adds one only while running is true. The hint appears 3 seconds after the page loads.

A number of milliseconds where the Duration belongs is E0308, mismatched types, so the unit is always written out:

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

#[derive(Signals, Serialize, Deserialize)]
struct Clock {
    tenths: i32,
}

let tenths = Clock::tenths();
// A number of milliseconds where a `Duration` belongs.
let clock = div::<Clock>().on_interval(100, tenths.set(tenths + 1));

The type does not bound the length. on_interval panics on a period under 1 millisecond, which would run the statement as often as the browser lets a timer run. Both methods panic on a time longer than 2^31 - 1 milliseconds, about 24.8 days, which the browser's timer cannot wait. The panic happens when the element is built, so a test that builds the page finds it.

Reacting to a change

effect runs its statement when the element is added, and again whenever a signal the statement reads changes. The signals it depends on are the ones the statement reads when it runs, so there is no list of dependencies to keep in step. A signal read only after an action's response arrives is not recorded. on_signal_change names the signal to watch, for a statement that does not read it, such as an action call that saves a list each time the list changes. T is the signal's value type and R says where the signal is reached from, such as the page root or a list item, so any signal of the page fits.

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

#[derive(Signals, Serialize, Deserialize)]
struct Search {
    query: String,
    long: bool,
    edits: i32,
}

let (query, long, edits) = (Search::query(), Search::long(), Search::edits());
let signals = Search { query: String::new(), long: false, edits: 0 };
let page = Page::new("Search", signals).child(
    div()
        // Reads `query`, so it runs again whenever `query` changes.
        .effect(long.set(query.char_count().gt(20)))
        // Does not read `query`, so it names the signal to watch.
        .on_signal_change(query, edits.set(edits + 1))
        .child(input().bind(query))
        .child(p().show(long).text("Try fewer words")),
);

A signal of another page is E0308, as it is for every method that takes a Sig<S, ..>.

The clock and random numbers

FunctionValue
Expr::now() -> Expr<S, f64>The browser's current time, in milliseconds since the Unix epoch
Expr::random_below(bound: impl IntoExpr<S, i32>) -> Expr<S, i32>A random integer from 0 up to but not including bound, drawn by the browser
use hypersig::html::{button, div, span};
use hypersig::{Expr, Page, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Dice {
    face: i32,
    rolled_at: f64,
}

let (face, rolled_at) = (Dice::face(), Dice::rolled_at());
let page = Page::new("Dice", Dice { face: 1, rolled_at: 0.0 }).child(
    div()
        // A number from 0 to 5, plus one.
        .child(
            button()
                .on_click(face.set(Expr::random_below(6) + 1).then(rolled_at.set(Expr::now())))
                .text("Roll"),
        )
        .child(span().bind_text(face.to_text()))
        // Milliseconds since the Unix epoch, read from the browser's clock.
        .child(span().bind_text(Expr::now().to_fixed(0))),
);

Neither value exists on the server, so the first HTML leaves a binding that reads either one empty, and the browser fills it in. In the first HTML of the page above, the <span> that shows the time is empty, and the one that shows the face holds 1.

Example: saving a draft

The editor below focuses its field when it loads, counts every change to the text however it was made, and notes the time every 30 seconds:

use std::time::Duration;

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

#[derive(Signals, Serialize, Deserialize)]
struct Editor {
    text: String,
    saved_at: f64,
    edits: i32,
    dirty: bool,
}

hypersig::node_ref!(const FIELD: NodeRef<Editor>);

let editor = div::<Editor>()
    // Focus the field when the page loads.
    .on_load(FIELD.focus())
    // Count every change to `text`, however it was made.
    .on_signal_change(
        Editor::text(),
        Editor::edits().set(Editor::edits() + 1).then(Editor::dirty().set(true)),
    )
    // Every 30 seconds, note the time of the save.
    .on_interval(
        Duration::from_secs(30),
        Editor::saved_at().set(Expr::now()).then(Editor::dirty().set(false)),
    )
    .child(input().node_ref(FIELD).bind(Editor::text()))
    .child(p().show(Editor::dirty()).text("Unsaved changes"));

Next, Keyboard patterns moves focus with the arrow keys, and Actions sends a statement's values to the server.