Commit Redux

A software development blog in commit-sized retrospectives

Pseudodrafts with Stimulus.js

Thursday May 15 2025 • 01:36 PM

In my last commit, I added the first bit of JavaScript to this blog, following the principle of progressive enhancement.

Andy Bell explains it like this:

Progressive enhancement is a design and development principle where we build in layers which automatically turn themselves on based on the browser’s capabilities. Enhancement layers are treated as off by default, resulting in a solid baseline experience that is designed to work for everyone.

We do this with a declarative approach which is already baked in to how the browser deals with HTML and CSS. For JavaScript — which is imperative — we only use it as an experience enhancer, rather than a requirement, which means only loading when the core elements of the page — HTML and CSS — are already providing a great user experience.

I’m using JavaScript to store the contents of the editor in localStorage when I’m drafting a new post. This way refreshing the page or navigating away won’t wipe the contents of a post before I publish. To do this I’m using Stimulus.js.

Stimulus is a great library for handling JavaScript interactions, or, as the team at 37signals puts it, for “sprinkling” interactivity throughout HTML. It enhances static HTML by providing a set of annotations (HTML element attributes) like data-controller and data-action which connect JavaScript objects to those elements.

From the Stimulus documentation:

These JavaScript objects are called controllers, and Stimulus continuously monitors the page waiting for HTML data-controller attributes to appear. For each attribute, Stimulus looks at the attribute’s value to find a corresponding controller class, creates a new instance of that class, and connects it to the element.

You can think of it this way: just like the class attribute is a bridge connecting HTML to CSS, Stimulus’s data-controller attribute is a bridge connecting HTML to JavaScript.

With Stimulus, I’ll be able to slowly (progressively) add features to the blog. For now, this works out as a very primitive implementation of a drafts feature. Later on, it would be nice to have a preview for the rendered Markdown.