Autofocus first input when a Turbo modal opens (Stimulus)

992
0

A modal that opens without focusing an input is a tiny annoyance that adds up. In Hotwire apps, modals often swap in via Turbo Frames, which means the DOM is injected after navigation. Stimulus is ideal here: attach an autofocus controller to the modal container and focus the first matching input on connect(). This also works when a frame replacement re-renders the form due to validation errors, keeping the experience smooth. I keep it conservative: don’t steal focus if the user is already typing somewhere else, and avoid focusing hidden/disabled inputs. This is a small UX polish that makes modals feel deliberate and professional.