Skip to content

Commit

Permalink
feat: Update lifecycle and mutation (#4000)
Browse files Browse the repository at this point in the history
* feat: Update lifecycle and mutation

The goal is to support "add reorder" that happen in the same mutation.

* add test for _x_isInit
  • Loading branch information
Matsa59 authored Feb 2, 2024
1 parent 9556727 commit 4c2397c
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 8 deletions.
20 changes: 13 additions & 7 deletions packages/alpinejs/src/lifecycle.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,18 @@ export function interceptInit(callback) { initInterceptors.push(callback) }
export function initTree(el, walker = walk, intercept = () => {}) {
deferHandlingDirectives(() => {
walker(el, (el, skip) => {
intercept(el, skip)

initInterceptors.forEach(i => i(el, skip))

directives(el, el.attributes).forEach(handle => handle())

el._x_ignore && skip()
if (!el._x_isInit) {
intercept(el, skip)

initInterceptors.forEach(i => i(el, skip))
directives(el, el.attributes).forEach(handle => handle())
}

if (el._x_ignore) {
skip()
} else {
el._x_isInit = true
}
})
})
}
Expand All @@ -96,5 +101,6 @@ export function destroyTree(root) {
walk(root, el => {
cleanupAttributes(el)
cleanupElement(el)
delete el._x_isInit
})
}
1 change: 0 additions & 1 deletion packages/alpinejs/src/mutation.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,6 @@ function onMutate(mutations) {
for (let node of addedNodes) {
// If the node was eventually removed as part of one of his
// parent mutations, skip it
if (removedNodes.has(node)) continue
if (! node.isConnected) continue

delete node._x_ignoreSelf
Expand Down
30 changes: 30 additions & 0 deletions tests/cypress/integration/mutation.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,36 @@ test('can pause and queue mutations for later resuming/flushing',
}
)

test('add and move element are been initialized',
html`
<div x-data="{
foo: 0,
bar: 0,
test() {
container = document.createElement('div')
this.$root.appendChild(container)
alpineElement = document.createElement('span')
alpineElement.setAttribute('x-data', '{init() {this.bar++}}')
alpineElement.setAttribute('x-init', 'foo++')
container.appendChild(alpineElement)
container.removeChild(alpineElement)
container.appendChild(alpineElement)
}
}">
<span id="one" x-text="foo"></span>
<span id="two" x-text="bar"></span>
<button @click="test">Test</button>
</div>
`,
({ get }) => {
get('span#one').should(haveText('0'))
get('span#two').should(haveText('0'))
get('button').click()
get('span#one').should(haveText('1'))
get('span#two').should(haveText('1'))
}
)

test('does not initialise components twice when contained in multiple mutations',
html`
<div x-data="{
Expand Down

0 comments on commit 4c2397c

Please sign in to comment.