日本語

Toasts from the server

A handler adds a toast with a patch on the list of toasts, and a failed call can show the server's message as a toast.

Accessibility

A toast from the server goes into the same list as one the browser pushes, so the Toaster shows it in the same aria-live="polite" region, and a screen reader reads it once it finishes what it is reading. The keys are those of the Toast page. A toast that is already in the list when the page loads is part of the first HTML, so a screen reader reads it with the page and does not announce it.

This page has no live demo, because this site is static files and has no server to answer a call. The Toast page shows the toaster running.

Adding a toast from a handler

The toasts are a Vec<Toast> field of the page's signals, so a handler adds one with a list patch on that field. Sig::patch_append adds items after the ones the browser holds, so the toasts the visitor already sees stay:

impl<S, T: Serialize> Sig<S, Vec<T>, Root> {
    pub fn patch_append(self, items: &[T]) -> ListPatch<S>;
}

impl<S: Signals> From<ListPatch<S>> for Patches<S>;

A handler returns the ListPatch<S> itself, or a Patches<S> that joins it with other patches, such as the signal the handler saved. Build each toast with Toast::new, description, and variant, as on the Toast page. push and push_expr are statements the browser runs, so a handler does not use them. List patches covers the other patches of a list.

Patch on toastsWhat the visitor sees
patch_append(&[toast])The new toast after the ones on screen
patch_prepend(&[toast])The new toast before the ones on screen
patch(vec![toast])Only the new toast: the ones on screen are replaced

The HTTP

A click on Save in the example below sends the call, and the handler's answer carries the patch. The answer is 200 with content-type: text/event-stream, and the browser applies the patch as it arrives:

POST /save
accept: text/event-stream
hypersig-call: 1
content-type: application/json

null

HTTP/1.1 200 OK
content-type: text/event-stream

Actions covers the request and the answer in full.

Showing the server's message when a call fails

When a call fails, on_error passes the server's message to the browser as an Expr<S, String>. Toast::push_expr adds a toast built from it in the browser: start from a literal toast with Expr::lit and put the message in its description with Expr::with(Toast::body(), message):

let failed = Toast::new("Save failed").variant(ToastVariant::Destructive);
let call = SAVE.call().on_error(|message| {
    Toast::push_expr(App::toasts(), Expr::lit(&failed).with(Toast::body(), message))
});

Busy and failed calls covers on_error and the message it receives.

Ids from the server and from the browser

Each toast has an id that tells it apart while the list changes, and nothing outside Toast sets it. Toast::new on the server counts down from -1, so every toast made in one process has its own id below 0. push and push_expr in the browser give one more than the highest id in the list, and 1 where no id is above 0. A toast from the server and one from the browser therefore never share an id, whichever order they arrive in.

What fails to compile

patch_append on toasts takes &[Toast], so a bare message is E0308, mismatched types:

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

#[derive(Signals, Serialize, Deserialize)]
struct App {
    toasts: Vec<Toast>,
}

async fn save((): (), (): ()) -> Patches<App> {
    // The list holds toasts, so a bare message is not one.
    App::toasts().patch_append(&["Saved"]).into()
}

Toast is #[non_exhaustive] and its id is private, so a toast written as a struct literal, with an id chosen by hand, is E0639:

use hypersig_ui::{Toast, ToastVariant};

// A toast's id is set by `Toast::new` alone.
let saved = Toast {
    title: "Saved".into(),
    body: String::new(),
    tone: ToastVariant::Default,
};

A handler returns Patches<S> of the page the action belongs to, so a patch on another page's toasts is E0308 too.

What is not checked

Nothing checks which patch a handler uses. patch in place of patch_append replaces the toasts on screen, so a toast the visitor has not read yet disappears. Sending one Toast value twice, or a clone of it, puts two toasts with one id in the list; the browser tells them apart by position and writes a warning to the console. After 2³¹ toasts in one process the server's ids start again from -1.

Example: saving with a toast

The page starts with a welcome toast in its signals, which is in the first HTML. Save calls the action, whose handler appends a toast, and a failed call shows the server's message:

use axum::Router;
use hypersig::html::div;
use hypersig::{Action, Expr, Page, Patches, Signals};
use hypersig_ui::{ButtonSize, ButtonVariant, Toast, ToastVariant, Toaster, button};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct App {
    toasts: Vec<Toast>,
}

hypersig::routes! {
    fn pages(Router<()>);
    action SAVE: Action<App> = post "/save" => save;
}

// The server adds its toast after the ones the browser already shows.
async fn save((): (), (): ()) -> Patches<App> {
    App::toasts()
        .patch_append(&[Toast::new("Saved").description("Your changes are live.")])
        .into()
}

// A failed call shows the server's message under the title.
let failed = Toast::new("Save failed").variant(ToastVariant::Destructive);
let call = SAVE.call().on_error(|message| {
    Toast::push_expr(App::toasts(), Expr::lit(&failed).with(Toast::body(), message))
});

// A toast in the first signals is in the first HTML.
let signals = App { toasts: vec![Toast::new("Welcome back")] };
let html = Page::new("App", signals)
    .child(
        div().child(
            button(ButtonVariant::Default, ButtonSize::Default).on_click(call).text("Save"),
        ),
    )
    .child(Toaster::new(App::toasts()))
    .render();
let _app: Router = pages(Router::new());

Toast covers the toaster and toasts pushed from the browser. Patches and List patches cover everything else a handler can send.