日本語

Events

Each event method writes a statement into an attribute of the element, and the runtime runs it on that DOM event or key.

Running a statement on an event

El::on, fn on(self, event: Event, stmt: impl IntoStmt<S>) -> Self, runs stmt each time event reaches the element. Each Event stands for a DOM event, and the common ones have a method of their own:

EventDOM eventMethod
Clickclickon_click
DoubleClickdblclickon_double_click
Inputinputon_input
Changechangeon_change
Submitsubmiton_submit
KeyDownkeydown, any keyon_key for one key
Focusfocusinnone
Blurfocusouton_blur
MouseEntermouseenternone
MouseLeavemouseleavenone
Loadthe element enters the documenton_load
Visiblethe element enters the viewporton_visible

Each method below is on with its event, so button().on_click(stmt) and button().on(Event::Click, stmt) do the same.

Clicks

on_click and on_double_click take the statement as impl IntoStmt<S> and return the element:

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

#[derive(Signals, Serialize, Deserialize)]
struct Photo {
    likes: i32,
    zoomed: bool,
}

let likes = Photo::likes();

let like = button::<Photo>().on_click(likes.set(likes + 1)).text("Like");
let picture = div::<Photo>().on_double_click(Photo::zoomed().toggle()).text("Double-click to zoom");

Typing

on_input runs on every edit of a text field. on_change runs on the DOM's change, which a text field fires when focus leaves it after its text changed, and a checkbox or a <select> fires on each choice. A field bound with bind already writes its signal, so these are for work beyond keeping the signal equal to the field:

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

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

let query = Search::query();
let keystrokes = Search::keystrokes();

let field = input::<Search>()
    .bind(query)
    // Each edit of the text.
    .on_input(keystrokes.set(keystrokes + 1))
    // Focus leaves the field after its text changed.
    .on_change(Search::committed().set(query));

Submitting a form

on_submit runs on a <form>'s submit. The runtime calls preventDefault first, so the browser does not load another page, and the statement decides what happens:

use hypersig::html::{attr, button, form, input};
use hypersig::{Page, Signals, Stmt};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Tags {
    draft: String,
    tags: Vec<String>,
}

let draft = Tags::draft();
let add = Tags::tags().push(draft.trim()).then(draft.set(""));

// Enter in the field and a click on the button both submit the form.
let new_tag = form::<Tags>()
    .on_submit(Stmt::when(!draft.trim().is_empty(), add))
    .child(input().bind(draft))
    .child(button().attr(attr::TYPE, "submit").text("Add"));

A form that the server validates and answers is a Form, which Forms covers.

Focus

Event::Focus listens for focusin, which runs when focus enters the element or one inside it from outside. on_blur listens for focusout, and runs when focus leaves the element and everything inside it. Focus moving between two elements inside runs neither, so a group of fields can hold one state while the visitor is anywhere in it:

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

#[derive(Signals, Serialize, Deserialize)]
struct Address {
    street: String,
    city: String,
    editing: bool,
}

let editing = Address::editing();

// Tab from the street to the city keeps focus inside the `div`,
// so neither statement runs.
let fields = div::<Address>()
    .on(Event::Focus, editing.set(true))
    .on_blur(editing.set(false))
    .child(input().bind(Address::street()))
    .child(input().bind(Address::city()))
    .child(p().show(editing).text("Editing the address"));

The pointer

Event::MouseEnter and Event::MouseLeave run when the pointer enters and leaves the element. They have no method of their own, so they go through on:

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

#[derive(Signals, Serialize, Deserialize)]
struct Map {
    hovered: String,
}

let hovered = Map::hovered();
let pin = |city: &'static str| -> El<Map> {
    span()
        .on(Event::MouseEnter, hovered.set(city))
        .on(Event::MouseLeave, hovered.set(""))
        .text(city)
};

let map = div::<Map>()
    .child(pin("Kyoto"))
    .child(pin("Nara"))
    .child(p().show(!hovered.is_empty()).bind_text(hovered));

Entering the document and the viewport

on_load runs once per element: for an element of the first HTML when the runtime starts, and for one added later when it is added, as the element of a new list item is or one that when puts back. A stream that sends changes made elsewhere opens from here, as Streams shows.

on_visible runs when the element is added in view, and again each time it enters the viewport after leaving it. An element hidden by show is out of view, so showing it again in view runs the statement. The browser decides with an IntersectionObserver, and a browser without one never runs it. List patches uses it to load the next page of a list.

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

#[derive(Signals, Serialize, Deserialize)]
struct Story {
    comments_open: bool,
    times_opened: i32,
    read_to_end: bool,
}

let opened = Story::times_opened();

let story = article::<Story>()
    .child(button().on_click(Story::comments_open().toggle()).text("Comments"))
    // `when` adds the element each time the condition turns true,
    // so `on_load` runs on each opening.
    .child(when(
        Story::comments_open(),
        div().on_load(opened.set(opened + 1)).text("No comments yet."),
    ))
    // Runs each time the last paragraph scrolls into view.
    .child(p().on_visible(Story::read_to_end().set(true)).text("The end."));

Waiting for a pause

on_debounced, fn on_debounced(self, event: Event, quiet: Duration, stmt: impl IntoStmt<S>) -> Self, runs stmt once event has stopped firing for quiet. Each new event restarts the wait, so an action behind it runs once per pause rather than once per keystroke:

use std::time::Duration;

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

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

let query = Search::query();

let field = input::<Search>()
    .bind(query)
    // Runs once the visitor has stopped typing for 300 ms.
    .on_debounced(Event::Input, Duration::from_millis(300), Search::searched().set(query));

The browser's timer waits at most 2^31 - 1 milliseconds, about 24.8 days, and the types do not limit the Duration, so a longer quiet panics when the element is built.

Two statements on one event

Calling on, or one of its methods, twice for the same event joins the two statements with then, so the second runs after the first. on_debounced joins the same way, so a field can do something on every keystroke and something else after a pause:

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

#[derive(Signals, Serialize, Deserialize)]
struct Draft {
    saved: bool,
    saves: i32,
}

let saves = Draft::saves();

let save = button::<Draft>()
    .on_click(Draft::saved().set(true))
    // A second statement for the same event runs after the first.
    .on_click(saves.set(saves + 1))
    .text("Save");

Keys

on_key, fn on_key(self, shortcut: impl Into<Shortcut>, stmt: impl IntoStmt<S>) -> Self, runs stmt when the key is pressed while focus is in the element. The key is a Key, such as Key::Enter or Key::Char('k'), or a Shortcut that a Key method makes with a modifier, such as Key::Char('k').primary(). The runtime calls preventDefault for a key it matches.

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

#[derive(Signals, Serialize, Deserialize)]
struct Editor {
    title: String,
    body: String,
    saved: bool,
}

let title = Editor::title();

let editor = div::<Editor>()
    // Ctrl+S, or Command+S on a Mac. A plain `s` still types in the fields.
    .on_key(Key::Char('s').primary(), Editor::saved().set(true))
    .child(input().bind(title).on_key(Key::Escape, title.set("")))
    .child(textarea().bind(Editor::body()));

How the modifiers match

  • A Key alone matches only while Ctrl, Alt, and Meta are all released. ctrl, alt, meta, and shift require that modifier, and primary requires Command on Apple platforms and Ctrl elsewhere.
  • Ctrl, Alt, and Meta match exactly: Key::Char('k').ctrl() runs on Ctrl+K and not on Ctrl+Alt+K. Shift matches exactly for a named key, so Key::Enter leaves Shift+Enter to a <textarea>.
  • A Key::Char already says whether Shift was held, as 'K' and '?' do on a US layout, so Shift is compared only where shift asks for it, and the character is then compared without regard to case.
  • On macOS, Option changes the character a key produces, so a Key::Char with alt does not match there.

Keys a text field keeps

A text field inside the element keeps the keys it edits text with, unless Ctrl, Alt, Meta, or primary is part of the shortcut. Those keys are a character, Space, Backspace, Delete, the left and right arrows, Home, and End, and in a <textarea> or an editable element also Enter and the up and down arrows. A handler on the field itself still takes them, as the Escape on the title field above does. Where several elements around the focus have handlers, the nearest one with a shortcut that matches runs, and the ones further out do not.

Keys anywhere on the page

Page::on_key takes the same arguments and applies to the whole page. It is the outermost handler, so it runs wherever focus is and while nothing has focus, unless a handler nearer the focus matched the key first:

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

#[derive(Signals, Serialize, Deserialize)]
struct Docs {
    help: bool,
}

let help = Docs::help();

let page = Page::new("Docs", Docs { help: false })
    // Runs wherever focus is, and while nothing has focus.
    .on_key(Key::Char('?'), help.toggle())
    .on_key(Key::Escape, help.set(false))
    .child(div().show(help).text("Press ? or Escape to close this help."));

Arrow-key navigation inside a list and moving focus with a key are built from these handlers and node refs, which Keyboard patterns covers.

A statement from another page

Every event method takes an IntoStmt<S> with the element's own S, so a statement over another page's signals is a compile error:

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

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

#[derive(Signals, Serialize, Deserialize)]
struct Settings {
    dark: bool,
}

// error[E0277]: `Stmt<Settings>` is not a statement on the page whose signals are `Counter`
let toggle = button::<Counter>().on_click(Settings::dark().toggle());

What the types leave unchecked

Nothing checks that the event can reach the element. A <div> with on_submit and no form inside it never runs the statement, and nothing reports it.

Events from timers and scripts

A statement can also run on a timer, after a signal changes, or on an event a script dispatches. Timers and reactions covers on_interval, on_timeout, effect, and on_signal_change, and JavaScript libraries covers on_custom with a CustomEvent.

on_context_menu runs a statement where the visitor right-clicks, in place of the browser's own menu, and hands it the position as an Expr<S, Point>. Context menu opens a menu of actions there.

A chat composer

The composer sends on submit, clears on Escape, and shows that the visitor is typing from the moment the field gets focus until half a second after the last keystroke:

use std::time::Duration;

use hypersig::html::{Event, Key, form, input};
use hypersig::Signals;
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Chat {
    draft: String,
    sent: i32,
    typing: bool,
}

let draft = Chat::draft();
let sent = Chat::sent();

let composer = form::<Chat>()
    // Runs after `preventDefault`, so the page does not reload.
    .on_submit(sent.set(sent + 1).then(draft.set("")))
    .child(
        input()
            // Two-way: typing writes `draft`, and setting `draft` rewrites the field.
            .bind(draft)
            .on_key(Key::Escape, draft.set(""))
            .on(Event::Focus, Chat::typing().set(true))
            .on_debounced(Event::Input, Duration::from_millis(500), Chat::typing().set(false)),
    );

Next

Binding form controls keeps a form control and a signal equal in both directions.