Stimulus
Stimulus adds behavior to the server's HTML. The HTML names the controller, its elements and its events, and the controller is a small class.
Adding a controller
Create a file in src/controllers/. Its name is its identifier:
| File | Identifier in HTML |
|---|---|
src/controllers/reset_form_controller.ts |
data-controller="reset-form" |
src/controllers/bridge/passkey_controller.ts |
data-controller="bridge--passkey" |
src/controllers/index.ts finds every *_controller.ts with Vite's
import.meta.glob and registers it with
stimulus-vite-helpers, so there is nothing else to edit:
const application = Application.start();
registerControllers(application, import.meta.glob("./**/*_controller.ts", { eager: true }));
While vp dev runs, saving a controller replaces the running one in every open page, the phone apps' included,
without reloading it: vite-plugin-stimulus-hmr (in
vite.config.ts) registers the new class again, so the old instances disconnect and new ones connect. A controller
that cleans up in disconnect() (below) survives that as it survives Turbo. To check, save a controller: vp dev
prints hmr update /src/controllers/…, not page reload.
// src/controllers/counter_controller.ts
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
static targets = ["input", "count"];
static values = { max: { type: Number, default: 280 } };
static classes = ["over"];
declare readonly inputTarget: HTMLTextAreaElement;
declare readonly countTarget: HTMLElement;
declare maxValue: number;
declare readonly overClass: string;
update() {
const left = this.maxValue - this.inputTarget.value.length;
this.countTarget.textContent = String(left);
this.countTarget.classList.toggle(this.overClass, left < 0);
}
}
<div data-controller="counter" data-counter-max-value="140" data-counter-over-class="text-error">
<textarea class="textarea" data-counter-target="input" data-action="input->counter#update"></textarea>
<span data-counter-target="count"></span>
</div>
In TypeScript, declare each target, value and class that the static lists create, so the type checker
knows them.
Rules that keep controllers working under Turbo
Turbo swaps pages, caches them and morphs them, so an element, and its controller, connects and disconnects many times.
- Whatever
connect()creates (a timer, a library instance, a listener),disconnect()removes. - Listen with
data-actionin the HTML. Stimulus adds and removes those listeners for you, including onwindowanddocument:resize@window->gallery#layout. - Keep state in values (
data-counter-max-value), not in fields. The server can render them, and a morph keeps them. React to changes inmaxValueChanged(). - Get elements from targets, never
document.querySelector. Put CSS classes instatic classesso the HTML chooses them (daisyUI'stext-error,hidden). - One job per controller (
reset-form,clipboard,dialog), never one controller per page. - Turbo's events work in
data-actiontoo:turbo:submit-end->reset-form#reset.
Use the server first. A link, a form, a frame or a stream needs no JavaScript. Stimulus is for what only the browser can do: focus, the clipboard, opening a dialog, a third-party widget.
Reference: https://stimulus.hotwired.dev/reference/controllers
daisyUI and Stimulus
Many daisyUI components work with no JavaScript: <dialog class="modal">, <details class="dropdown">, the
swap input, and tabs. Use those as they are. Write a controller for what HTML
cannot do alone, such as opening a <dialog> from a button (this.dialogTarget.showModal()).
When it does not work
| Symptom | Cause |
|---|---|
| Nothing happens, no error | The file name and the identifier don't match (foo_bar_controller.ts is foo-bar) |
Missing target element |
The target is outside the controller's element, or missing; check hasXTarget for optional ones |
| Works on first load, not after a link | The code is in DOMContentLoaded or turbo:load, not in a controller |
| A saved controller reloads the whole page in development | The file does not end in _controller.ts, or index.ts no longer has const application = Application.start(), which the plugin looks for |
| Listeners or timers pile up | disconnect() does not undo connect() |