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

Faceted Search with Stimulus and Turbo Frames
10 December 2024

Harness the power of Stimulus and Turbo Frames to drive a simple but powerful faceted search solution

Stimulus - Video Progress Tracker with LocalStorage
29 October 2024

Store ephemeral user state like video playback progress in localStorage

Stimulus - Image Upload Previews with `URL.createObjectURL`
17 September 2024

Create client-side previews of files using URL.createObjectURL

Cookies
essential