Skip to content

Commit

Permalink
🐛 Fixes Regression in Mutation handling (alpinejs#4450)
Browse files Browse the repository at this point in the history
* 🧪 Adds test for improperly cleaned Elements

* 🐛 Prevents Moved elements from being cleaned up
  • Loading branch information
ekwoka authored Nov 28, 2024
1 parent f283554 commit cb08c46
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 14 deletions.
33 changes: 21 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions packages/alpinejs/src/mutation.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ function onMutate(mutations) {

mutations[i].addedNodes.forEach(node => {
if (node.nodeType !== 1) return
if (node._x_marker) return

addedNodes.push(node)
})
Expand Down Expand Up @@ -198,7 +197,7 @@ function onMutate(mutations) {

for (let node of addedNodes) {
if (! node.isConnected) continue

if (node._x_marker) return;
onElAddeds.forEach(i => i(node))
}

Expand Down
27 changes: 27 additions & 0 deletions tests/cypress/integration/mutation.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ test('no side effects when directives are added to an element that is removed af
get('span').should(haveText('0'))
}
)

test(
"previously initialized elements are not reinitialized on being moved",
html`
Expand All @@ -243,3 +244,29 @@ test(
get("[x-test]").should(haveText("1"));
}
);

test(
"previously initialized elements are not cleaned up on being moved",
html`
<script>
let count = 0;
document.addEventListener("alpine:init", () => {
Alpine.directive("test", (el, _, { cleanup }) => {
el.textContent = "Initialized";
cleanup(() => {
el.textContent = "Cleaned up";
});
Alpine.nextTick(() => {
el.parentNode.replaceChildren(el);
})
});
});
</script>
<div x-data>
<div class="bg-red-300 w-32 h-32" x-test></div>
</div>
`,
({ get }) => {
get("[x-test]").should(haveText("Initialized"));
}
);

0 comments on commit cb08c46

Please sign in to comment.