ReviewOS

stacks/stx

Teleport: target lookup is one-shot — silently fails when target is created later in the page lifecycle

#1728
Closed glennmichael123 opened this 23 days ago · 0 comments
23 days ago

Summary

<Teleport to="#modals"> generates an inline <script> that, when it runs, calls document.querySelector('${target}'). If the target element doesn't exist yet, the script logs a warning and bails — there's no retry, no MutationObserver, no deferred attempt. The teleport silently doesn't work.

Reproducer

<!-- Page-level layout that creates #modals lazily (e.g., after onMount of a
     LayoutShell component does `document.body.append(modalsRoot)`) -->
<Teleport to="#modals">
  <div>I should land in #modals</div>
</Teleport>

<!-- Elsewhere: -->
<script client>
  onMount(() => {
    const root = document.createElement('div')
    root.id = 'modals'
    document.body.appendChild(root)
  })
</script>

The teleport script runs inline at the position it's emitted. If that's before the onMount that creates #modals, the warning fires and the teleported content stays in the source placeholder forever — even after #modals appears.

Root cause

packages/stx/src/teleport.ts:68-72:

const targetEl = document.querySelector('${target}');
if (!targetEl) {
  console.warn('[stx] Teleport target not found: ${target}');
  return;
}

One-shot lookup. No way to recover if the target is added by JS that runs later in the page lifecycle.

Impact

  • Teleport-to-late-target patterns silently fail.
  • Less common but very confusing when it happens — the warning fires once and is easy to miss in a noisy console.
  • Affects any pattern where a layout-level "portal root" is created programmatically rather than declared in the source HTML.

In the common case (#modals declared in a layout template), the target IS already in DOM by the time the teleport script runs, so this bug is dormant for most users. But the failure mode is silent enough that "it just doesn't work and I don't know why" is the user experience when they hit it.

Suggested fix

Two layers:

  1. Retry once with requestAnimationFrame. Cheap and handles the case where the target is added later in the same render pass:

    function tryMount() {
      const targetEl = document.querySelector('${target}');
      if (targetEl) { /* existing mount logic */; return; }
      // Defer one frame and try again. Don't loop indefinitely.
      requestAnimationFrame(tryMount2);
    }
    function tryMount2() {
      const targetEl = document.querySelector('${target}');
      if (targetEl) { /* mount */; return; }
      console.warn('[stx] Teleport target not found: ${target}');
    }
    tryMount();
  2. Optionally: opt-in <Teleport to="#x" wait> that uses MutationObserver. Bounded — give up after N seconds — for users whose target genuinely shows up arbitrarily late.

(1) alone is probably enough for the 95% case.

Environment

  • stx main
  • Bun 1.3.13

Sign in to comment on this issue.