Skip to content

Commit

Permalink
fix(jsx): unsubscribe when removing a parent element (artalar#919)
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperskei authored Sep 27, 2024
1 parent be53c6c commit ec71d33
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 14 deletions.
10 changes: 5 additions & 5 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"core-js": "^3.37.1",
"history": "^5.3.0",
"husky": "^8.0.3 ",
"linkedom": "^0.16.10",
"linkedom": "^0.18.5",
"lit": "^3.1.2",
"microbundle": "^0.15.1",
"react": "^18.2.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/jsx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"csstype": "^3.1.2"
},
"devDependencies": {
"linkedom": "^0.16.4"
"linkedom": "^0.18.5"
},
"author": "artalar",
"maintainers": [
Expand Down
3 changes: 2 additions & 1 deletion packages/jsx/src/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -516,10 +516,11 @@ test('ref mount and unmount callbacks order', async () => {
)

mount(parent, component)
await sleep()
parent.remove()
await sleep()

assert.equal(order, [2, 1, 0, 2, 1, 0])
assert.equal(order, [2, 1, 0, 0, 1, 2])
})

test('style object update', () => {
Expand Down
18 changes: 12 additions & 6 deletions packages/jsx/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,14 +263,20 @@ export const reatomJsx = (ctx: Ctx, DOM: DomApis = globalThis.window) => {
new DOM.MutationObserver((mutationsList) => {
for (let mutation of mutationsList) {
for (let removedNode of mutation.removedNodes) {
let list = unsubscribesMap.get(removedNode as any)
if (list) {
list.forEach((fn) => fn())
unsubscribesMap.delete(removedNode as any)
}
/**
* @see https://stackoverflow.com/a/64551276
* @note A custom NodeFilter function slows down performance by 1.5 times.
*/
const walker = DOM.document.createTreeWalker(removedNode, 1)

do {
const node = walker.currentNode as Element
unsubscribesMap.get(node)?.forEach((fn) => fn())
unsubscribesMap.delete(node)
} while (walker.nextNode())
}
}
}).observe(target, {
}).observe(target.parentElement!, {
childList: true,
subtree: true,
})
Expand Down

0 comments on commit ec71d33

Please sign in to comment.