#1570·turbo

Stream focus preservation overrides newly focused input during unrelated update

Author: XymistCreated Sep 25, 2026Updated Sep 25, 2026

Summary

In Turbo 8.0.23, StreamMessageRenderer's withPreservedFocus can override a new focus target chosen after stream rendering starts but before its animation-frame continuation runs. This also happens when the stream updates an entirely unrelated element: neither the previously focused element nor the newly focused input needs to be replaced.

Minimal reproduction

Run this in a browser page importing @hotwired/[email protected]:

javascript
import { renderStreamMessage } from "@hotwired/turbo";

document.body.innerHTML = `
  <div id="modal" tabindex="-1"><input id="email"></div>
  <span id="notification">Before</span>
`;

const modal = document.getElementById("modal");
const email = document.getElementById("email");
modal.focus();
renderStreamMessage(`
  <turbo-stream action="update" target="notification">
    <template>After</template>
  </turbo-stream>
`);
email.focus();

const { promise, resolve } = Promise.withResolvers();
requestAnimationFrame(resolve);
await promise;

console.log(document.getElementById("notification").textContent.trim()); // After
console.log(document.activeElement.id); // Actual: modal; expected: email

All IDs are unique. This does not require Rails, Bootstrap, autofocus attributes, or a replaced form. In a real form, the unexpected blur can commit a tag-style input; the user's next Enter then acts on the now-empty input rather than committing the intended text.

Cause and possible fix

withPreservedFocus captures the active element before rendering and restores its ID after around(...), whenever that element differs from the later active element. The comparison does not distinguish focus lost because of a replaced node from focus deliberately moved to another element.

A local patch limits restoration to when the later active element is null or document.body, matching the no-active-element check already used by withAutofocusFromFragment:

javascript
if (restoreFocusTo &&
    (activeElementAfterRender == null || activeElementAfterRender == document.body)) {
  // existing restoration logic
}

Verified in Chromium with three regression cases:

  1. An unrelated stream must not steal focus from a newly focused input (fails unpatched, passes patched).
  2. Replacing the focused input with another input having the same ID must still restore focus (passes both).
  3. Replacing the old input after focus has moved elsewhere must respect that new target (fails unpatched, passes patched).

Related discussion: #1248. This reproduction isolates stream-message focus preservation and works without duplicate IDs or replacing the focused subtree in the first case.