日本語

Node refs

A node ref names one element, so that a statement can focus it, select its text, scroll it into view, or open it as a popover or a dialog. The page covers declaring one, its statements, and the mistakes that rendering catches.

Declaring a node ref

A NodeRef<S> names one element of a page whose signals are S, so that a statement can call a DOM method on it, such as focus(). Declare it at module level with node_ref!, as node_ref!(const FIELD: NodeRef<Search>), and attach it with El::node_ref, fn node_ref(self, node_ref: NodeRef<S>) -> Self.

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

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

// At module level, outside every function.
hypersig::node_ref!(const FIELD: NodeRef<Search>);

let search = div::<Search>()
    .child(input().node_ref(FIELD).bind(Search::query()))
    .child(button().on_click(FIELD.focus()).text("Search"));

The name is the constant's path: the module path that module_path!() gives, then the identifier, such as shop::search::FIELD. Two constants have two paths, so their names differ.

FIELD.focus() is a statement like any other. A click on the button runs it, and the browser moves focus to the field.

What fails to compile

node_ref! inside a function body fails to compile with E0425, cannot find value FIELD in module self. Two functions of one module could otherwise each declare a constant with one identifier and give two elements one name.

use hypersig::html::{El, input};
use hypersig::{NodeRef, Signals};
use serde::{Deserialize, Serialize};

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

fn search_field() -> El<Search> {
    // Inside a function body, where `self::FIELD` does not reach the constant.
    hypersig::node_ref!(const FIELD: NodeRef<Search>);
    input().node_ref(FIELD).bind(Search::query())
}

The type parameter ties the reference to one page. A NodeRef<Search> on an element of a page whose signals are Cart is E0308, mismatched types:

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

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

#[derive(Signals, Serialize, Deserialize)]
struct Cart {
    coupon: String,
}

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

// `FIELD` names an element of the page whose signals are `Search`.
let coupon = input::<Cart>().node_ref(FIELD).bind(Cart::coupon());

The statements

Each method takes the reference by value, since NodeRef is Copy, and returns a Stmt<S>. A statement goes wherever one is taken, such as on_click, on_key, or a timer, and then runs another after it.

MethodWhat the browser does
fn focus(self) -> Stmt<S>Focuses the element after the next render
fn blur(self) -> Stmt<S>Removes focus from the element
fn select(self) -> Stmt<S>Selects the text of an <input>
fn scroll_into_view(self) -> Stmt<S>Scrolls the element into view
fn show_popover(self) -> Stmt<S>Shows the element if it is a closed popover
fn hide_popover(self) -> Stmt<S>Hides the element if it is an open popover. Where focus was inside it, the browser returns focus to the element that had it before the popover opened

NodeRef::id, fn id(self) -> Id, gives an element id spelled as the reference's name. A component that names its element by a NodeRef uses it for the id that an aria-* attribute points at.

Inside a list

Each item of a list may carry the same constant. Inside a list item the browser looks for the element in the same item first, so one NodeRef serves every item. Below, each Rename button selects the title in its own card:

use hypersig::html::{button, each_keyed, input, li, ul};
use hypersig::{NodeRef, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Card {
    id: i64,
    title: String,
}

#[derive(Signals, Serialize, Deserialize)]
struct Board {
    cards: Vec<Card>,
}

hypersig::node_ref!(const TITLE: NodeRef<Board>);

// Every item carries `TITLE`, and each button selects the title in its own item.
let board = ul::<Board>().child(each_keyed(
    Board::cards(),
    |card| card.at(Card::id()),
    |card| {
        li().child(input().node_ref(TITLE).bind(card.at(Card::title())))
            .child(button().on_click(TITLE.select()).text("Rename"))
    },
));

One name on one element

The compiler does not see which elements carry a name. Outside a list template, one constant on two elements that the browser can both reach makes Page::render and El::render panic with two elements carry the node ref ... where the runtime can reach both. A test that renders the page finds it. A fixed id from El::id on two elements panics the same way.

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

#[derive(Signals, Serialize, Deserialize)]
struct Search {
    query: String,
    filter: String,
}

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

let signals = Search { query: String::new(), filter: String::new() };
let page = Page::new("Search", signals).child(
    div()
        .child(input().node_ref(FIELD).bind(Search::query()))
        // A second element with the same name.
        .child(input().node_ref(FIELD).bind(Search::filter())),
);
// Panics: "two elements carry the node ref `...::FIELD` where the runtime can reach both".
let _ = page.render();

One element takes one node ref. A second call of El::node_ref, or El::node_ref together with El::foreign, panics when the element is built. A Fragment sent again in a patch is rendered on its own, so the server cannot compare it with the rest of the page. For that case, the browser writes a warning to the console when the patch adds a name or an id that another element it can reach already carries. The name of a FileInput is looked up apart from these names, so it never collides with one.

Dialogs

A DialogRef<S> names a <dialog>. Declare it with dialog_ref!, which takes the same form as node_ref!. fn dialog(self) -> El<S> builds the empty <dialog> element the constant names, and it is the only way to attach one, so its statements always act on a dialog:

MethodWhat the browser does
fn show_modal(self) -> Stmt<S>Opens the dialog with showModal(), unless it is open. The browser makes the rest of the page inert, moves focus into the dialog, and closes it on Escape
fn close(self) -> Stmt<S>Closes the dialog, if it is open. The browser returns focus to the element that had it before the dialog opened
use hypersig::html::{button, div, input};
use hypersig::{DialogRef, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Palette {
    query: String,
}

hypersig::dialog_ref!(const PALETTE: DialogRef<Palette>);

let page = div::<Palette>()
    .child(button().on_click(PALETTE.show_modal()).text("Commands"))
    .child(
        // The `<dialog>` element that `PALETTE` names.
        PALETTE
            .dialog()
            .child(input().bind(Palette::query()))
            .child(button().on_click(PALETTE.close()).text("Close")),
    );

A DialogRef and a NodeRef share one set of names, and rendering panics where the dialog of one constant sits twice where the browser can reach both.

Example: a stopwatch

The stopwatch below counts tenths of a second with on_interval. The reset button stops it, sets the count to zero, and moves focus to the start button through the node ref START.

Result

stopwatch.rs
use std::time::Duration;

use hypersig::html::{div, span};
use hypersig::style::Style;
use hypersig::style::pattern::hstack;
use hypersig::style::value::{FontWeight, rem};
use hypersig::{Page, Signals, Stmt, if_else};
use hypersig_ui::{ButtonSize, ButtonVariant, button};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
pub(super) struct Stopwatch {
    running: bool,
    tenths: i32,
}

hypersig::node_ref!(const START: NodeRef<Stopwatch>);

pub(super) fn page() -> Page<Stopwatch> {
    let running = Stopwatch::running();
    let tenths = Stopwatch::tenths();
    let seconds = tenths.to_f64() / 10.0;
    Page::new(
        "Stopwatch",
        Stopwatch {
            running: false,
            tenths: 0,
        },
    )
    .child(
        div()
            .css(hstack(rem(1)))
            .on_interval(
                Duration::from_millis(100),
                Stmt::when(running, tenths.set(tenths + 1)),
            )
            .child(
                span()
                    .css(
                        Style::new()
                            .min_width(rem(4))
                            .font_size(rem(1.5))
                            .font_weight(FontWeight::Number(600.0)),
                    )
                    .bind_text(seconds.to_fixed(1)),
            )
            .child(
                button(ButtonVariant::Default, ButtonSize::Default)
                    .node_ref(START)
                    .on_click(running.toggle())
                    .bind_text(if_else(
                        running,
                        "Stop",
                        "Start",
                    )),
            )
            .child(
                button(ButtonVariant::Outline, ButtonSize::Default)
                    .on_click(running.set(false).then(tenths.set(0)).then(START.focus()))
                    .text("Reset"),
            ),
    )
}

Next, Timers and reactions covers on_interval and the other statements that run without an event, and Keyboard patterns moves focus with the arrow keys.