日本語

List patches

Patches that add, replace, or remove items of a list without sending the rest of it, and a feed that loads more items as the visitor scrolls.

The four list patches

patch sends a list whole, so a chat that sends each message with patch sends every earlier one again. A ListPatch<S> sends only the items that change, and the browser applies it to the list it holds, so the server does not keep a copy of that list. Four methods of a Vec signal build one:

MethodWhat the browser does with its list
patch_append(self, items: &[T])Adds items after the items it holds
patch_prepend(self, items: &[T])Adds items before the items it holds
patch_upsert(self, items: &[T], key)Replaces the first item with each new item's key, and adds an item whose key no item has at the end. Of two items in items with one key, the later wins
patch_remove(self, keys: &[K], key)Removes each item whose key is one of keys

Each returns a ListPatch<S>. key is a closure impl FnOnce(Item<S, T>) -> E that builds an expression of the item, as in each_keyed. The closure runs once on the server to build the expression, and the browser evaluates it for each item and compares the keys. ListPatch::and adds the changes of another ListPatch, applied after its own, and Patches::list adds a ListPatch to a batch beside signals and fragments.

use hypersig::{Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Message {
    id: i32,
    body: String,
}

#[derive(Signals, Serialize, Deserialize)]
struct Room {
    messages: Vec<Message>,
    oldest: i32,
}

let messages = Room::messages();
let by_id = |message: hypersig::Item<Room, Message>| message.at(Message::id());
let incoming = Message { id: 42, body: "hello".to_owned() };

// One new message, as a stream's next event.
let new: Patches<Room> = messages.patch_append(&[incoming]).into();

// An older page goes above the messages on screen, which stay where they are.
let older = vec![Message { id: 30, body: "earlier".to_owned() }];
let page: Patches<Room> = Patches::new()
    .list(messages.patch_prepend(&older))
    .signals(Room::oldest().patch(30));

// An edit replaces the message with its id, and a deletion removes it.
let edited = Message { id: 42, body: "hello again".to_owned() };
let edit: Patches<Room> = messages
    .patch_upsert(&[edited], by_id)
    .and(messages.patch_remove(&[7], by_id))
    .into();

assert_eq!(new.items_of(messages)[0].body, "hello");

As with patch, only a Vec signal reached from the page's struct has these methods. The list of a list item's field is a Sig<S, Vec<T>, Local>, and calling one of them on it is a compile error, E0599, because the server cannot name the item the browser is rendering. The state of a list item covers that state in the browser.

use hypersig::html::{each_keyed, li, ul};
use hypersig::{Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Card {
    id: i32,
    tags: Vec<String>,
}

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

let board = ul::<Board>().child(each_keyed(
    Board::cards(),
    |card| card.at(Card::id()),
    |card| {
        // error[E0599]: no method named `patch_append` found for struct `Sig<Board, Vec<String>, hypersig::Local>` in the current scope
        let tag: Patches<Board> = card.at(Card::tags()).patch_append(&["urgent".to_owned()]).into();
        li()
    },
));

Items added above the ones on screen

Items added before an each_keyed list keep the items already on screen where they were: the browser scrolls the nearest scrollable ancestor by the height of the new items. Chrome's scroll anchoring does the same once the list is scrolled, but not at the very top, and a list that loads older items is at the top when it loads them. Sig::prepend does the same in the browser. A list drawn with each matches its elements by position, so its first element shows the first new item and nothing scrolls.

What the types leave unchecked

Nothing checks that the key of patch_upsert or patch_remove is the key the list's each_keyed draws with, or that the keys are unique. A key that differs finds no item, so an upsert adds the item at the end instead of replacing it, and a removal removes nothing. Two items with one key in an each_keyed list are matched by position, and the browser writes a warning naming the key to the console. An item that holds an integer outside -2^53 to 2^53 makes the method panic when the patch is built. In a test, items_of and removed_keys_of read what a batch adds and removes, and removed_keys_of takes the key closure, so the test also checks the key the browser compares.

Loading more as the visitor scrolls

A feed that loads its next page as the visitor reaches the bottom is built from on_visible, patch_append, and a page signal. An element after the items runs on_visible when it comes into view, which calls a GET action with the page signal as its argument. The handler appends the page's items with patch_append, so the items already in the browser are not sent again, and patches page to the next number and more to whether a full page came back. indicator sets loading while the call runs, and show hides the element during the load and once more is false. When the new items still leave it in view, showing it again runs on_visible again and loads the next page.

use hypersig::html::{div, each_keyed, li, ul};
use hypersig::{Action, Patches, Signals};

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

#[derive(Signals, Serialize, Deserialize)]
struct Feed {
    posts: Vec<Post>,
    // The page the next load asks for: 1 at first, because page 0 is in the HTML.
    page: i32,
    loading: bool,
    more: bool,
}

hypersig::routes! {
    fn pages(Router<()>);
    action MORE: Action<Feed, i32> = get "/feed/more" => more;
}
const PER_PAGE: usize = 20;

let feed = div::<Feed>()
    .child(ul().child(each_keyed(
        Feed::posts(),
        |post| post.at(Post::id()),
        |post| li().bind_text(post.at(Post::title())),
    )))
    // Comes into view below the last post, and stays hidden while a load runs.
    .child(
        div()
            .show(Feed::more().and(!Feed::loading()))
            .on_visible(MORE.call_with(Feed::page()).indicator(Feed::loading())),
    );

async fn more((): (), page: i32) -> Patches<Feed> {
    let posts = load_page(page);
    Patches::new().list(Feed::posts().patch_append(&posts)).signals(
        Feed::page()
            .patch(page + 1)
            .and(Feed::more().patch(posts.len() == PER_PAGE)),
    )
}

let app: axum::Router = pages(axum::Router::new());

Next, Fragments sends HTML for a part of the page, and Streams sends list patches as they happen, such as a chat's new messages.