Auto Sort

by Julian Rubisch

To install this controller, run this command in your Rails app directory in the terminal:

bin/rails app:template LOCATION=https://betterstimulus.com/templates/dom-manipulation/auto-sort

Usage

Configuration

Attribute Default Description Required
data-sort-attribute-name-value - Name of the data attribute on each child element to use for sorting yes
data-sort-attribute-type-value 'number' Data type of the data attribute to use for sorting no

Rationale

Suppose you have a stream of DOM elements coming in asynchronously via Websockets, for example using Turbo Streams.

By the very nature of Websockets, these may come in unordered. Or, maybe you want to apply a different ordering thanby creation time. In both cases, you can employ a Stimulus controller to do the sorting for you. This is done by binding a MutationObserver to an element and have it watch changes to the element’s children. Whenever a child is added or removed, they are re-sorted using a configurable data attribute.

In the chat example above, the first case is exaggerated by a long delay between messages and made more visible using animations (which are of course optional).

In the second example, we assume that cards containing student names are coming in unordered, and we want to sort them alphabetically by their name.