Turbo 8 Morphing: Page Refreshes That Keep Your Place

Turbo 8 Morphing: Page Refreshes That Keep Your Place

Turbo 8 morphing promises to refresh a page without losing your place, we wanted to know what exactly survives, so we built a long list, opened things, typed things, and refreshed it with Turbo 8.0.23, with morph and without.

<%# app/views/layouts/application.html.erb, inside head %>
<%= turbo_refreshes_with method: :morph, scroll: :preserve %>
<%= yield :head %>

First the refresh without morph, and all is back to zero, scroll on top, focus lost. Then with morph and scroll preserve, and now we are still down in the list where we scrolled, the same row has the focus, we even compared the DOM nodes and they are the very same objects, ok, this promise it keeps.

Now what did not survive even with morph. A details block which we opened came back closed. Text typed into a field was replaced by the value from server, also in the field which had focus at that moment, our note just disappeared. An element which we added by JavaScript, like third party widgets do, was removed. The block with data-turbo-permanent stayed open, but its content was old, it showed the first count while the page already had a newer one, permanent means really permanent.

<div id="filters" data-turbo-permanent>
  <%= render "filters" %>
</div>

Ids we tested by adding a new row on top of the list while the cursor was in row 10. With ids the focus stayed on row 10. Without ids the focus ended on row 11, a different row, and a person would continue typing into wrong place, so dom_id on every item is not decoration.

<li id="<%= dom_id(task) %>">

With Stimulus the controller on a surviving element did not connect again, connect count stayed 1, but the value changed callback ran, therefore logic which depends on new data we keep in valueChanged. And the markup which controller had added in connect was wiped by morph and not added back, check this if you wrap some date picker.

static values = { total: Number }

totalValueChanged() {
  this.render()
}

See also: building UIs with Hotwire and small Stimulus controllers.