日本語

Elements and attributes

A page is a tree of El values built with Rust functions and rendered to HTML on the server. The tags, the attribute names, and the ids that attributes point at are checked when the program compiles.

Elements

The html module has one function per common tag, such as div(), p(), and button(). Each has the signature fn div<S>() -> El<S> and returns an El<S>, where S is the page's signal struct. The methods of El take the element and return it, so a tree is one expression, and render returns its HTML.

use hypersig::html::{Id, a, div, h1, p};
use hypersig::{Route, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Profile {}


hypersig::routes! {
    fn pages(Router<()>);
    const ADA: Route = "/ada" => ada;
}

let card = div::<Profile>()
    .id(Id::new("ada"))
    .child(h1().text("Ada Lovelace"))
    .child(
        p().text("Wrote the first program. ")
            .child(a().href(ADA.link()).text("Read more")),
    );

assert_eq!(
    card.render(),
    r#"<div id="ada"><h1>Ada Lovelace</h1><p>Wrote the first program. <a href="/ada">Read more</a></p></div>"#,
);

div::<Profile>() names the page's signal struct because nothing else in this code tells the compiler which page the element belongs to. An element passed to Page::new(...).child(...), or to a function that takes an El<Profile>, gets its S from there, which is why the Quick start writes div(). The children of an element take its S the same way, so only the outermost element of a tree written on its own needs the ::<Profile>.

An element belongs to one page

El::child has the signature fn child(self, child: impl IntoNode<S>) -> Self. IntoNode<S> is implemented for an El<S>, a Node<S>, and text, all with the same S. An element built for another page's signals carries that page's S, so it cannot sit inside this page, and neither can the signals and actions it reads:

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

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

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

fn badge() -> El<Shelf> {
    span().bind_text(Shelf::count().to_text())
}

// error[E0277]: `El<Shelf>` is not a child of an element on the page whose
// signals are `Detail`
let detail = div::<Detail>().child(badge());

Text and children

text appends static text, and child appends an element or a string. children appends each item of an iterator, and an Option counts as zero or one child. The renderer writes &, <, and > in text as &amp;, &lt;, and &gt;, so text from a visitor shows as text.

use hypersig::html::{li, small, ul};

let names = ["Ada", "Grace", "Alan"];
let note: Option<&str> = None;

let list = ul::<()>()
    .children(names.iter().map(|name| li().text(*name)))
    // An `Option` adds zero or one child.
    .children(note.map(|text| li().child(small().text(text))));
assert_eq!(list.render(), "<ul><li>Ada</li><li>Grace</li><li>Alan</li></ul>");

The types do not check which elements may sit inside which. One case panics when child runs: a p given a child at which the HTML parser ends a paragraph, such as a div, a ul, or another p, outside a button, a table, or a template, because the browser would end the p there and move the element after it. Write such a p as a div. Any other nesting the HTML standard forbids is written as given, and the browser repairs it as it parses.

Attributes

attr has the signature fn attr(self, name: Attr, value: impl Into<String>) -> Self and sets a plain attribute, such as .attr(attr::PLACEHOLDER, "Name"). The name is an Attr. The module html::attr holds one for each attribute of HTML, SVG, and ARIA, so a misspelled name stops the build. A name outside those lists, such as data-lat or an attribute of a custom element, is written hypersig::attr!("data-lat"), which checks it at compile time.

A tag with no function of its own, such as an SVG element or a custom element, is el(hypersig::tag!("geo-map")). el takes a Tag, and tag! checks at compile time that the name is letters, digits, -, _, ., and :, starting with a letter, and that it is not script, style, base, or link, in any case. The first two run their text as code, base moves every relative URL of the page to another origin, and link loads from the host its href names. Page::stylesheet and Page::icon write the <link>s a page needs, as Styling and The page and its head show.

use hypersig::html::{attr, el, input};

let name = input::<()>()
    .attr(attr::TYPE, "text")
    .attr(attr::PLACEHOLDER, "Name");
assert_eq!(name.render(), r#"<input type="text" placeholder="Name">"#);

// A tag and attributes with no constant, each checked at compile time.
let map = el::<()>(hypersig::tag!("geo-map"))
    .attr(hypersig::attr!("data-lat"), "35.68")
    .attr(hypersig::attr!("data-lng"), "139.76");
assert_eq!(
    map.render(),
    r#"<geo-map data-lat="35.68" data-lng="139.76"></geo-map>"#,
);

The value is any string, and nothing checks it against the attribute or the attribute against the tag, so type="emial" or a placeholder on a div is written as given: the browser shows an <input> with an unknown type as a text field, and a placeholder on a div does nothing. Setting the same attribute twice on one element panics, from attr or from a method that sets it, such as El::role, because the browser reads the first of two and ignores the second.

Names an Attr cannot hold

Neither the constants nor attr! give an Attr for the names below, ignoring case, so attr, bind_attr, and attr_when cannot write them. attr! with one of them fails to compile with the rule it breaks:

use hypersig::html::img;

// error[E0080]: evaluation panicked: an `on*` attribute runs a script; attach
// a handler with the `on_*` methods
let photo = img::<()>().attr(hypersig::attr!("onerror"), "alert(1)");
NameWritten instead by
id and classEl::id and El::class, below and in Values that follow the signals
An attribute whose value names another element by its id, such as for, aria-describedby, aria-controls, and commandforThe methods that take an Id, such as label_for(&EMAIL) and aria_describedby(&[&HINT]), so a reference cannot be spelled apart from its target
roleEl::role, from a Role, so a misspelled role stops the build too
A name starting with data-hs-Nothing: hypersig reserves these names for its own methods
href, src, poster, and srcsetEl::href, El::src, El::poster, and El::srcset, from a Link or a SafeUrl, a URL whose scheme cannot run a script
A name starting with on, such as onclickThe on_* methods, such as on_click, which attach a statement in its place
srcdoc, action, formaction, xlink:href, data, http-equiv, ping, imagesrcset, background, manifest, codebase, archive, classid, and longdescNothing: they load a URL or a document and have no method of their own. A form sends its values through an action call, as Forms shows
styleEl::css and El::bind_style, which write the element's CSS
attributeNameNothing: with the value href, an SVG animation would write into a link
A name holding a character other than a letter, a digit, -, _, ., and :Nothing: such a character would end the name and start another attribute

Ids and the attributes that point at them

El::id takes an Id, which you declare once, such as const EMAIL: Id = Id::new("email"). Id::new fails to compile in a const when the name is empty or holds whitespace. The element and each attribute that points at it read the same value, so the two cannot be spelled apart. El::role takes a Role, the WAI-ARIA role a screen reader announces the element by.

use hypersig::html::{Id, Role, attr, div, input, label, p};

// Each id is declared once, and the element and its references share it.
const EMAIL: Id = Id::new("email");
const HINT: Id = Id::new("email-hint");

let field = div::<()>()
    .child(label().label_for(&EMAIL).text("Email"))
    .child(
        input()
            .id(EMAIL)
            .aria_describedby(&[&HINT])
            .attr(attr::TYPE, "email"),
    )
    .child(p().id(HINT).text("We never share it."))
    .child(div().role(Role::Status).text("Saved"));
assert_eq!(
    field.render(),
    concat!(
        r#"<div><label for="email">Email</label>"#,
        r#"<input id="email" aria-describedby="email-hint" type="email">"#,
        r#"<p id="email-hint">We never share it.</p>"#,
        r#"<div role="status">Saved</div></div>"#,
    ),
);
MethodAttribute it writes
label_for(&Id)for on a <label> or an <output>
aria_labelledby(&[&Id]), aria_describedby, aria_controls, aria_owns, aria_details, aria_flowto, aria_errormessageThe aria-* attribute of the same name, a list of ids separated by spaces
aria_activedescendant(&Id)aria-activedescendant
command_for(&Id), popover_target(&Id)commandfor, popovertarget
datalist(&Id), form_owner(&Id)list on an <input>, form on a control
headers(&[&Id]), itemref(&[&Id])headers on a table cell, itemref

Id::with_key(key) names one of several elements, such as a row: ROW.with_key(7) is row-7. Id::from_text builds an id from text at run time, such as the anchor of a heading.

Nothing checks that the page holds the element a reference names. The browser ignores a reference to an id no element carries, so the control reads with no label or description. Three mistakes panic in Page::render: two elements carrying one id from Id::new, with or without the keys of with_key; an element inside a list template with an id, which every item would repeat; and a second El::id call on one element, which panics where it is called. Two ids alike where either comes from Id::from_text render, because the text may come from data visitors stored, and an anchor or a label then reaches the first of them. A page handler that panics answers nothing, so the browser reports an empty response.

URLs

href, src, and poster take an impl IntoHref<S>: a Link or a Url from a Route, which Links and redirects covers, or a SafeUrl for an address the router does not serve, which Values the types do not check covers. A fixed URL is written as a plain attribute, and one that reads signals follows them. srcset takes pairs of a SafeUrl and a Candidate, the width or the pixel density the image is drawn for.

The src of an <iframe>, an <embed>, or a <frame> shows the page at that URL inside this one, so it comes from the program: src panics on those tags when the URL reads signals. A Candidate::Density that is not a finite number above 0 panics too.

A team page

The page below lists the members of a team. Each card is a component, a function that returns an El<Team>, and is named by its heading through an id with the member's key. The photo comes from a SafeUrl, and the profile link from the route MEMBER, so a link with a parameter of the wrong type fails to compile.

use hypersig::html::{El, Id, a, article, attr, h2, h3, img, li, p, section, ul};
use hypersig::{Page, Route, SafeUrl, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Team {}

hypersig::routes! {
    fn pages(Router<()>);
    const MEMBER: Route<u32> = "/members/{id}" => member;
}

struct Member {
    id: u32,
    name: &'static str,
    job: &'static str,
    photo: SafeUrl,
}

const HEADING: Id = Id::new("team");
const NAME: Id = Id::new("member");

/// One member's card, named by its heading for a screen reader.
fn card(member: &Member) -> El<Team> {
    let name = NAME.with_key(member.id);
    li().child(
        article()
            .aria_labelledby(&[&name])
            .child(img().src(member.photo.clone()).attr(attr::ALT, ""))
            .child(h3().id(name).text(member.name))
            .child(p().text(member.job))
            .child(a().href(MEMBER.url(member.id)).text("Profile")),
    )
}

let members = [
    Member { id: 1, name: "Ada", job: "Engineer", photo: SafeUrl::new("/photos/1.jpg") },
    Member { id: 2, name: "Grace", job: "Admiral", photo: SafeUrl::new("/photos/2.jpg") },
];
let page = Page::new("Team", Team {}).child(
    section()
        .aria_labelledby(&[&HEADING])
        .child(h2().id(HEADING).text("Team"))
        .child(ul().children(members.iter().map(card))),
);
assert!(page.render().contains(concat!(
    r#"<li><article aria-labelledby="member-1"><img src="/photos/1.jpg" alt="">"#,
    r#"<h3 id="member-1">Ada</h3><p>Engineer</p><a href="/members/1">Profile</a></article></li>"#,
)));

Next, The page and its head wraps a tree in a document, and Values that follow the signals makes its text and attributes change in the browser. Components covers functions like card.