Essentials / Turbo Streams

Docs Essentials

Turbo Streams

As mentioned in the Overview, Turbo sends text/vnd.turbo-stream.html in the Accept header of the form submissions it intercepts, which tells our handlers that they may respond with Turbo Streams instead of a redirect. The RequestExt trait checks for it:

rust
use laravel::model::create;
use laravel::prelude::*;
use laravel::validation::ValidRequest;
use turbo::{RequestExt, stream};

pub async fn store(post: Post, input: ValidRequest<StoreComment>) -> laravel::Result<Response> {
    let (form, request) = input.into_parts();
    let comment = create!(Comment { post_id: post.id, body: form.body }).await?;

    if request.wants_turbo_stream() {
        return Ok(stream::append("comments", view("comments.partials.comment", data! { comment })).into_response());
    }

    Ok(redirect!(posts::show, post.id).into_response())
}

A handler that validates its input takes a ValidRequest, which also hands over the request, since Valid and Request both read the request's body.

Keep the redirect for when Turbo isn't around, such as before its JavaScript loads. Turbo also follows the redirect fine, so Turbo Streams are an enhancement: return them when updating parts of the page gives a better experience than reloading it.

Building Streams

Each action has a function in the turbo::stream module that returns a Stream, and a stream is a response:

rust
use laravel::view::{Html, data, view};
use turbo::stream;

stream::append("comments", view("comments.partials.comment", data! { comment }));
stream::prepend("comments", html.clone());
stream::replace(&post, html.clone());         // target = post.dom_id(), so "post_42"
stream::update("counter", count.to_string()); // text is escaped
stream::before("comment_7", html.clone());
stream::after("comment_7", html);
stream::remove(&comment);
stream::refresh();

The target is an element's ID, or a model, whose DOM ID becomes the target.

The content is one of:

  • a View, such as a partial. view(..).fragment("form") renders a single block of a template, so a page and its streams may share a template;
  • Html, which is sent as it is;
  • a String or &str, which is escaped.
rust
use laravel::view::Html;
use turbo::stream;

let text = stream::update("greeting", "<b>Hi</b>");
let html = stream::update("greeting", Html::raw("<b>Hi</b>"));

assert_eq!(
    text.render()?.into_string(),
    r#"<turbo-stream action="update" target="greeting"><template>&lt;b&gt;Hi&lt;&#x2f;b&gt;</template></turbo-stream>"#,
);
assert_eq!(
    html.render()?.into_string(),
    r#"<turbo-stream action="update" target="greeting"><template><b>Hi</b></template></turbo-stream>"#,
);

Turbo Streams & Morph

Turbo 8 may morph the changed element instead of replacing it, which keeps its state, such as focus or a scroll position. Chain morph on a replace or update stream to send method="morph":

rust
use turbo::stream;

let stream = stream::replace("comment_7", "Updated").morph();

assert_eq!(
    stream.render()?.into_string(),
    r#"<turbo-stream action="replace" target="comment_7" method="morph"><template>Updated</template></turbo-stream>"#,
);

A refresh stream may morph and keep the scroll position too:

rust
use turbo::stream;

let stream = stream::refresh().morph().preserve_scroll();

assert_eq!(
    stream.render()?.into_string(),
    r#"<turbo-stream action="refresh" method="morph" scroll="preserve"></turbo-stream>"#,
);

Target Multiple Elements

Every action except refresh has an _all variant that takes a CSS selector and changes every element it matches:

rust
use turbo::stream;

let stream = stream::remove_all(".notification");

assert_eq!(
    stream.render()?.into_string(),
    r#"<turbo-stream action="remove" targets=".notification"></turbo-stream>"#,
);

Turbo Streams Combo

A response may hold several streams. turbo::streams takes them in order:

rust
use laravel::prelude::*;
use turbo::stream;

pub async fn destroy(comment: Comment) -> laravel::Result<Response> {
    let streams = turbo::streams([
        stream::remove(&comment),
        stream::update("flash", "Comment deleted."),
    ]);

    comment.delete().await?;

    Ok(streams.into_response())
}

Streams also collects from an iterator, so a handler may build streams in a loop:

rust
use turbo::{Streams, stream};

let streams: Streams = comments.iter().map(stream::remove).collect();

Custom Actions

stream::action builds a stream with any action, for Turbo's custom actions. Add a target, content and attributes as needed:

rust
use turbo::stream;

let stream = stream::action("log").attr("message", "Hello World");

assert_eq!(
    stream.render()?.into_string(),
    r#"<turbo-stream action="log" message="Hello World"></turbo-stream>"#,
);

target, targets, content and attr work on every stream. An attribute replaces one of the same name, and its value is escaped.