fix(toast): initialize toaster state in initialize() so pre-existing targets don't throw
Result
Problem
toaster_controller.js throws on page load whenever a toast target is already in the DOM at boot (e.g. a server-rendered flash message):
TypeError: Cannot read properties of undefined (reading 'set')
at toastTargetConnected (application.js)
at invokeControllerMethod
at targetConnected
Stimulus fires target lifecycle callbacks in this order for pre-existing targets:
initialize() → targetConnected() → connect()
The controller initializes _heights / _resizeObservers inside connect(), but toastTargetConnected() calls this._heights.set(...) and this._resizeObservers.set(...). For a toast present in the initial HTML, toastTargetConnected runs before connect, so this._heights is still undefined → the whole controller (and often the whole Stimulus application) blows up.
This only manifests when a <Toast> is rendered server-side inside the <Toaster> on first paint. Toasts created at runtime via the stream action / JS API connect after connect() has run, which is why it slips through interactive testing.
Fix
Move the state that toastTargetConnected touches into initialize(), which is guaranteed to run before any targetConnected:
_heights,_resizeObservers,_expandedare initialized ininitialize().connect()still sets_expanded = this.expandValue(values are read inconnect).- Added a single
this._reflow()at the end ofconnect()so server-rendered toasts get positioned: theirtoastTargetConnectedran before_listElexisted and_reflow()returned early via itsif (!this._listEl) returnguard.
No behavior change for runtime-created toasts.
Files
Both copies kept in sync:
gem/lib/ruby_ui/toast/toaster_controller.jsdocs/app/javascript/controllers/ruby_ui/toaster_controller.js
How to reproduce
Render a Toaster with a Toast already inside it on initial page load (a flash message), then load the page → TypeError in the console before the fix, clean after.