Premise
The official Turbo Stream guide states that
You can render any number of stream elements in a single stream message from a WebSocket, SSE or in response to a form submission.
That is true, but it is also too restrictive. In fact, Turbo will happily parse and execute any <turbo-stream>
element that is added to the DOM at any time. This means that we can also use it in a pure client-side scenario.
As we shall see, a declarative use of server rendered turbo stream tags can be a formidable way to power microinteractions.
Challenge
- Your job this time is to insert a suitable
<turbo-stream>
element into the provided HTML<template>
element here:
- then use the click handler to implement a progress bar animation only by cloning and inserting those
<turbo-stream>
elements: https://stackblitz.com/edit/turbo-streams-inline-tags?file=index.html%3AL55,app.js%3AL7 - the output should look like this:
Note: I’m using shoelace components here. The documentation for the progress bar can be found here.
Aside: If you’d like to explore this in a Rails specific context, take a look at Sean P. Doyle’s Turbo Stream Button repository: https://github.com/seanpdoyle/turbo_stream_button
Caveats
- You will have to deal with cloning
<template>
elements. If you’re not familiar with it too much, here’s a guide on MDN.
Teaser
- It’s obvious that this challenge is a bit far-fetched. This technique can be a powerful way to implement Optimistic UI patterns though. Can you think of any in your apps that could be a candidate for this?