Skip to content

Comments

Fix x-ref crash during child-element morph#4748

Merged
calebporzio merged 1 commit intomainfrom
fix/x-ref-skip-during-clone
Feb 16, 2026
Merged

Fix x-ref crash during child-element morph#4748
calebporzio merged 1 commit intomainfrom
fix/x-ref-skip-during-clone

Conversation

@calebporzio
Copy link
Collaborator

Summary

  • Fixes TypeError: Cannot read property '_x_refs' of undefined when calling Alpine.morph() on a child element (not the x-data root) that contains x-ref attributes
  • Wraps x-ref's inline handler with skipDuringClone() — the established Alpine pattern used by 10+ other directives
  • Adds Cypress test that morphs a child <section> containing x-ref and verifies state preservation + ref resolution

Problem

When morphing a child element, morph's cloneNode() runs directives on detached to elements whose parent chain has no [x-data] ancestor. closestRoot() returns undefined, and x-ref dereferences it → crash.

This affects htmx+Alpine users in production (reported in #3797, #3758, #3003).

Why skipDuringClone over a null guard

The PR #4744 proposed if (! root) return — a valid fix, but skipDuringClone is the Alpine-established pattern for "this directive doesn't need to run during clone." Refs on detached to elements are discarded anyway; post-morph, refs re-register on live DOM via the MutationObserver path.

Test plan

  • New test: morph child element with x-ref — no crash, state preserved, $refs resolves
  • All 35 morph tests pass
  • All 6 $refs tests pass
  • All 4 clone tests pass

Closes #3797. Alternative to #4744.

🤖 Generated with Claude Code

Wrap x-ref's inline handler with skipDuringClone() to prevent TypeError
when morph runs on a child element (not the x-data root). During morph,
cloneNode() runs directives on detached elements where closestRoot()
returns undefined. Refs re-register on live DOM via MutationObserver.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@calebporzio calebporzio merged commit cfcd08d into main Feb 16, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant