The page and its head
Page wraps the tree in the HTML document a handler sends, with the runtime, the initial signals, and the head that browsers, search engines, and link previews read.
The page
Page<S> wraps the tree in a full document. Page::new(title: impl Into<String>, signals: S) takes the title and the initial values of the signals, child appends to <body>, and render(&self) -> String returns the HTML a handler sends. Page::lang sets the lang of <html> from an IntlLocale or a LanguageTag, which the browser reads for hyphenation, the voice of a screen reader, and the fonts it picks. A page without it has no lang.
use hypersig::html::h1;
use hypersig::{IntlLocale, Page, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Notes {
count: i32,
}
let page = Page::new("Notes", Notes { count: 2 })
.lang(IntlLocale::En)
.child(h1().text("Notes"));
let html = page.render();
assert!(html.starts_with(r#"<!doctype html><html lang="en"><head>"#));
assert!(html.contains("<title>Notes</title>"));
assert!(html.contains(hypersig::RUNTIME_PATH));
assert!(html.ends_with("<h1>Notes</h1></body></html>"));The document holds the character set, a viewport for phones, an empty icon so that the browser does not request /favicon.ico, the title, and the script that loads the runtime, which reads the initial signal values from the page. Every binding is rendered with those values already applied, so text, visibility, classes, attributes, form values, list items, and conditional elements show before the runtime loads, and the runtime keeps the elements instead of building them again.
Page::render panics on a mistake the types cannot hold, such as two elements with one id from Id::new, a signal struct whose Serialize impl fails, or an integer outside -2^53 to 2^53, which the browser would round. In a debug build it also panics when Page::lang names the language of an IntlLocale and the page formats its plurals and dates only in others. The rustdoc of render lists every case. A test that renders each page finds them before a visitor does, as Testing a page without a browser shows.
Serving the page and the runtime
A page handler returns the Page, and the function routes! writes registers it on the router. The document loads the runtime from RUNTIME_PATH, and RouterExt::hypersig_runtime serves the file at that path.
use axum::Router;
use hypersig::html::h1;
use hypersig::{Page, Route, RouterExt, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Notes {
count: i32,
}
async fn notes((): (), (): ()) -> Page<Notes> {
Page::new("Notes", Notes { count: 2 }).child(h1().text("Notes"))
}
hypersig::routes! {
fn pages(Router<()>);
const NOTES: Route = "/" => notes;
}
// The routes of the block, and the runtime at `hypersig::RUNTIME_PATH`.
let app: Router = pages(Router::new()).hypersig_runtime();Nothing checks that the router calls hypersig_runtime. Without it, the request for the runtime gets a 404 that the browser's console shows, and the page stays as its first HTML drew it: nothing reacts to a click or a key. A page served under a path prefix loads the runtime from under that prefix, as Serving under a path prefix shows. In a debug build, an open tab reloads on its own when the development server restarts the server.
A title that follows the signals
Page::bind_title(expr) makes the tab's title follow a String expression, such as an unread count. The server writes its first value into <title>, and the runtime writes each later value into document.title. A search engine reads the HTML, so it shows the first value, and the card of OpenGraph keeps the title given to Page::new.
use hypersig::{Page, Signals, if_else};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Inbox {
unread: i32,
}
let unread = Inbox::unread();
let page = Page::new("Inbox", Inbox { unread: 3 }).bind_title(if_else(
unread.gt(0),
unread.to_text().concat(" unread - Inbox"),
"Inbox",
));
assert!(page.render().contains("<title>3 unread - Inbox</title>"));The expression must be a String. A number, such as the count itself, is a compile error until to_text turns it into text:
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Inbox {
unread: i32,
}
// error[E0277]: `Sig<Inbox, i32>` is not an expression of type `String` on
// the page whose signals are `Inbox`
let page = Page::new("Inbox", Inbox { unread: 3 }).bind_title(Inbox::unread());Search results and link previews
Page::description writes the summary a search result shows, and Page::icon the icon of the tab from an Asset, a URL written in the program. A canonical URL and the image of a link preview must be absolute, so Page::canonical and OpenGraph::image join a path to an Origin. OpenGraph takes the card's title, text, and URL from the page, so each is written once.
use hypersig::{Asset, OpenGraph, Origin, Page, Route};
#[derive(Signals, Serialize, Deserialize)]
struct Post {
title: String,
}
hypersig::routes! {
fn pages(Router<()>);
const POST: Route<u32> = "/posts/{id}" => post;
}
// The scheme and host, checked when the constant is compiled.
const SITE: Origin = Origin::new("https://blog.example.com");
let page = Page::new("Hello", Post { title: "Hello".to_owned() })
.description("The first post.")
.canonical(SITE, &POST.url(1))
.icon(Asset::new("/icon.svg"))
.open_graph(OpenGraph::new().site_name("Blog").image(SITE, "/og/1.png", "A wave"));
let html = page.render();
assert!(html.contains(r#"<meta property="og:url" content="https://blog.example.com/posts/1">"#));The Origin constant fails to compile when it holds more than the scheme, the host, and the port. An application that a proxy serves under a path such as /blog adds that path with Origin::under, which rejects a malformed prefix the same way:
use hypersig::Origin;
// error[E0080]: evaluation panicked: an origin ends at the host and port
const SITE: Origin = Origin::new("https://example.com/blog/");OpenGraph::image panics when the path does not start with /. Nothing checks that the router serves the image or the icon, and the browser's console shows the 404 of a missing icon. OpenGraph::kind sets og:type, which is website without it, and OpenGraph::locale sets og:locale from an OpenGraphLocale such as ja_JP.
Page::json_ld adds structured data that search engines read, written so that no string inside it can close the block. noindex and nofollow ask search engines to leave the page out of their results and not to follow its links. Page::alternate names the same page in another language, which Alternate pages covers.
use hypersig::{Page, Signals};
use serde::{Deserialize, Serialize};
use serde_json::json;
#[derive(Signals, Serialize, Deserialize)]
struct Post {}
let post = Page::new("Hello", Post {})
.json_ld(&json!({ "@type": "Article", "headline": "Hello" }));
assert!(post.render().contains(
r#"<script type="application/ld+json">{"@type":"Article","headline":"Hello"}</script>"#
));
// A page that search results should leave out, such as a cart.
let cart = Page::new("Cart", Post {}).noindex().nofollow();
assert!(cart.render().contains(r#"<meta name="robots" content="noindex, nofollow">"#));What else a page sets
The other methods of Page belong to the topics below.
| Methods | What they set | Page |
|---|---|---|
theme, global, style, stylesheet, css_when, css_match | Token values, rules by tag, stylesheets, and styles on <body> | Styling |
computed | A signal kept equal to an expression | Computed signals |
persist | A signal kept in localStorage | Signals kept across page loads |
on_key | A shortcut anywhere on the page | Events |
script | A <script type="module"> the page's elements need | JavaScript libraries |
csp_nonce, framing | A Content-Security-Policy nonce, and which pages may frame this one | Security |
runtime_src, render_under | Where the runtime loads from, and the path prefix of a static file | Static pages |
A blog post
The handler below answers each post with its language, summary, canonical URL, icon, and a card whose image is named after the post. A post the store does not hold answers None, which the router sends as a 404.
use axum::Router;
use hypersig::html::{article, h1, p};
use hypersig::{
Asset, IntlLocale, OpenGraph, OpenGraphType, Origin, Page, Route, RouterExt, Signals,
};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Post {
likes: i32,
}
hypersig::routes! {
fn pages(Router<()>);
const POST: Route<u32> = "/posts/{id}" => post;
}
const SITE: Origin = Origin::new("https://blog.example.com");
const ICON: Asset = Asset::new("/icon.svg");
/// The page of post `id`, with what search results and link previews show.
fn post_page(id: u32, title: &str, summary: &str, body: &str) -> Page<Post> {
Page::new(title, Post { likes: 0 })
.lang(IntlLocale::En)
.description(summary)
.canonical(SITE, &POST.url(id))
.icon(ICON)
.open_graph(
OpenGraph::new()
.kind(OpenGraphType::Article)
.site_name("Blog")
.image(SITE, format!("/og/{id}.png"), title),
)
.child(article().child(h1().text(title)).child(p().text(body)))
}
async fn post((): (), id: u32) -> Option<Page<Post>> {
// A post the store does not hold answers 404.
(id == 1).then(|| post_page(id, "Hello", "The first post.", "Hello, world."))
}
let app: Router = pages(Router::new()).hypersig_runtime();
let html = post_page(1, "Hello", "The first post.", "Hello, world.").render();
assert!(html.contains(r#"<meta property="og:url" content="https://blog.example.com/posts/1">"#));
assert!(html.contains(r#"<meta property="og:type" content="article">"#));Next, Values that follow the signals makes the page's text and attributes change in the browser. Routes covers the route POST and its parameter.