fix(toast): initialize toaster state in initialize() so pre-existing targets don't throw

Merged
PI
4mo ago
+49-17

Result

toast-ruby-ui

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, _expanded are initialized in initialize().
  • connect() still sets _expanded = this.expandValue (values are read in connect).
  • Added a single this._reflow() at the end of connect() so server-rendered toasts get positioned: their toastTargetConnected ran before _listEl existed and _reflow() returned early via its if (!this._listEl) return guard.

No behavior change for runtime-created toasts.

Files

Both copies kept in sync:

  • gem/lib/ruby_ui/toast/toaster_controller.js
  • docs/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.