日本語

Fragments

A fragment is a part of the page the server renders again and sends as HTML, which the browser merges into the element with the fragment's id.

Declaring a fragment

A Fragment is a part of the page the server can render again on its own. Its trait has three items: type Signals: Signals, the signal struct of its page; const ID: Id, the element id of its root; and fn render(&self) -> El<Self::Signals>. The fragment owns its element id, so the id in the first page and the id in a later patch cannot differ. fragment, fn fragment<F: Fragment>(fragment: &F) -> El<F::Signals>, renders it in the page with its root's id set to ID, replacing any id render gave it.

use hypersig::html::{El, Id, li, ul};
use hypersig::{Fragment, Patches, Signals, fragment};
use serde::{Deserialize, Serialize};

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

struct Cart {
    items: Vec<String>,
}

impl Fragment for Cart {
    type Signals = Shop;
    const ID: Id = Id::new("cart");

    fn render(&self) -> El<Shop> {
        ul().children(self.items.iter().map(|item| li().text(item.as_str())))
    }
}

let cart = Cart { items: vec!["tea".to_owned()] };

// In the page, the root carries the fragment's id.
assert_eq!(fragment(&cart).render(), r#"<ul id="cart"><li>tea</li></ul>"#);

// A handler sends the same fragment again, rendered from the new items.
let more = Cart { items: vec!["tea".to_owned(), "milk".to_owned()] };
let patches = Patches::new().element(&more);
assert!(patches.replaces::<Cart>());

Sending it again

Patches::element, fn element<F: Fragment<Signals = S>>(self, fragment: &F) -> Self, renders the fragment again and sends its HTML, with the CSS rules its elements use when they use css. The text and attributes the fragment's bindings show follow the signals in the browser once the patch arrives, as they do in the first page. A fragment of another page's signals is a compile error, E0271.

use hypersig::html::{El, Id, ul};
use hypersig::{Fragment, Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Shop {
    total: String,
}

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

// A fragment of the account page.
struct Orders;

impl Fragment for Orders {
    type Signals = Account;
    const ID: Id = Id::new("orders");

    fn render(&self) -> El<Account> {
        ul()
    }
}

// error[E0271]: type mismatch resolving `<Orders as Fragment>::Signals == Shop`
let patches = Patches::new()
    .signals(Shop::total().patch("¥1,200".to_owned()))
    .element(&Orders);

What changes in the page

The browser compares the HTML it receives with the element that has the fragment's id and rewrites only the parts that differ. An element without an id is matched with the next one of the same tag and name, so a message inserted before an input leaves the input and its text in place. Where a patch does replace the element that has focus, focus and the text selection move to the new element with the same id or name. The open attribute of a <details> and a <dialog> is left alone, so a section the visitor opened or a dialog a script showed stays as it was. A list or a condition inside the fragment whose template is unchanged keeps the items and the content the browser drew, with their focus and any text being typed in them.

Ids the server cannot compare

The server renders a fragment sent again on its own, so it cannot compare its ids with the rest of the page. The browser compares them once the patch is applied and writes a warning to the console when the patch adds an id that another element already carries. The same holds for the name of a NodeRef, which Node refs covers.

What the types leave unchecked

A fragment of a component that is a Part is rendered with its paths under the field of the part being answered. A batch built outside the handler or stream answering that part, such as in a task that broadcasts one batch to every page, cannot be sent to it: an action answers 500 Internal Server Error with the reason, and a stream ends. to_event_stream panics in that case.

The server sends the fragment's whole HTML each time, so a list that changes one item at a time costs less as a list signal drawn with each_keyed, which a list patch changes one item at a time, as examples/todo does.

A complete example

This search sends the query 200 ms after the visitor stops typing, and the handler answers with the result list rendered again as a fragment. The search field sits outside the fragment, so its text and focus stay as they were.

src/main.rs
use std::time::Duration;

use axum::Router;
use hypersig::html::{El, Event, Id, attr, input, li, ul};
use hypersig::{Action, Fragment, Page, Patches, Route, RouterExt, Signals, fragment};
use serde::{Deserialize, Serialize};

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

const FRUITS: &[&str] = &[
    "apple", "apricot", "banana", "cherry", "grape", "melon", "peach",
];

struct Results {
    query: String,
}

impl Fragment for Results {
    type Signals = Search;
    const ID: Id = Id::new("results");

    fn render(&self) -> El<Search> {
        ul().children(
            FRUITS
                .iter()
                .filter(|fruit| fruit.contains(self.query.as_str()))
                .map(|fruit| li().text(*fruit)),
        )
    }
}

hypersig::routes! {
    fn pages(Router<()>);
    const INDEX: Route = "/" => index;
    action SEARCH: Action<Search, String> = post "/search" => search;
}

async fn index((): (), (): ()) -> Page<Search> {
    let query = Search::query();
    Page::new(
        "Search",
        Search {
            query: String::new(),
        },
    )
    .child(
        input()
            .attr(attr::ARIA_LABEL, "Search fruit")
            .bind(query)
            .on_debounced(
                Event::Input,
                Duration::from_millis(200),
                SEARCH.call_with(query),
            ),
    )
    .child(fragment(&Results {
        query: String::new(),
    }))
}

async fn search((): (), query: String) -> Patches<Search> {
    Patches::new().element(&Results { query })
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let app = pages(Router::new()).hypersig_runtime();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app).await
}
This program needs a server, so this site shows it as code. It is built by cargo test from site/examples/ in the repository.

Next, Streams sends patches and fragments as changes happen on the server.