hotwired / turbo

The speed of a single-page web application without having to write any JavaScript
https://turbo.hotwired.dev
MIT License
6.62k stars 419 forks source link

Turbo morph not preserving stimulus values #1210

Open rbclark opened 5 months ago

rbclark commented 5 months ago

I am unsure if this issue is with Stimulus or Turbo, so I apologize if this is the wrong repo. I am using Turbo 8 morphing and I am noticing that all my controller values are reset when my page morphs. This behavior is a bit confusing since the connect callback is also skipped in these situations. I've included a simple example repo I used for testing this behavior here: https://github.com/rbclark/turbo-8-stimulus-bug-demo

In the video below I initially load the page and then after the first refresh morph the connected-value attribute disappears.

https://github.com/hotwired/turbo/assets/2308869/8f547b69-d407-4590-aac6-15df96d2e296

For now I have a global workaround added to my application.js to avoid this issue, although I'm not sure if it will have any other unforseen implications:

document.addEventListener("turbo:before-morph-attribute", (event) => {
  const {detail: {attributeName}} = event

  if (attributeName.startsWith("data-") && attributeName.endsWith("-value")) {
    event.preventDefault()
  }
})

With how well Stimulus works with Turbo normally, it would be great if this behavior just worked out of the box.

seanpdoyle commented 5 months ago

Thank you for opening this issue and for sharing a reproduction repository.

This feels related to several existing issues:

The events that you mention were introduced by https://github.com/hotwired/turbo/pull/1097 (as a successor to a commit (https://github.com/hotwired/turbo/pull/1019/commits/9944490a3c8aec0c5060401125cc8932e93a32df) that was ultimately reverted).

although I'm not sure if it will have any other unforseen implications

The unforeseen circumstances are certainly a risk. Over-committing to ignore all server-sent Stimulus Values feels safer than under-committing. I'm sure with time there will be some edge cases that will emerge.

it would be great if this behavior just worked out of the box.

Integration with Stimulus was the main driver behind that contribution. As the dust of the Turbo 8 release settles, I hope that there will bandwidth for a coordinated effort to expand built-in Morph integration for Stimulus and Trix (and therefore Action Text). Something that affords a configuration-less turn-key solution for most circumstances with some focused escape hatches when necessary.