Stimulus - Auto-Sorting

Use a MutationObserver to sort websocket messages that arrived out of order.

View Solution on Patreon
Stimulus - Auto-Sorting

Premise

In this challenge, we are going to tackle a common but often overlooked scenario: Resolving the ordering of websocket messages that arrive jumbled up. Think of a chat application where several people are typing in their messages and the backing web server is using multiple processes (or even multiple servers) to process the form submissions. There’s no guarantee whatsoever that messages arrive in the correct order at each of the participants, yet it’s crucial to understanding the conversation. We are going to take a look at how to resolve that.

Challenge

First up, let’s assume that each message has a timestamp of when it arrived at the server and that this timestamp is correct (i.e., can be used to sort the messages). To simulate the out-of-order arrival I’ve set up a procedure that slices a random element out of the messages array and transports them as Turbo Stream broadcasts over the websocket:

These messages are appended to a <ul> on the index page, where a sort Stimulus controller is already connected:

https://stackblitz.com/edit/stimulus-auto-sort?file=index.html%3AL42

To visualize this a bit, I’ve used the simple but effictive auto-animate Javascript library.

Your task is to conceive a Stimulus controller that handles the ordering of the messages as they come in:

https://stackblitz.com/edit/stimulus-auto-sort?file=index.html%3AL42,app.js,controllers%2Fsort_controller.js

Here’s a peek at the end result:

Auto-Sorting of Incoming Chat Messages

Caveats

You will need a MutationObserver, but be mindful of infinite loops. Think carefully of when to start, stop, and restart observing.

Teaser

Can you think of other ways to insert messages at the correct spot right before they are appended to the DOM?

More from

Stimulus - Orchestrate Complex UI Changes with Target Callbacks
07 May 2024

Use Stimulus target callbacks to dynamically update parts of your UI

Stimulus - Progressive Image Loading with Blurhash
23 April 2024

Improve Largest Contentful Paint using image blurhashes and Stimulus

Hotwire Combobox with Real Time Data
12 March 2024

Update combobox options using Websockets and Stimulus outlets

Cookies
essential