Skip to content

Commit

Permalink
feat: support attached shadow dom elements (#618)
Browse files Browse the repository at this point in the history
Original implementation did not properly handle nested shadow dom elements.

Updated the traversal to manually step through the dom to ensure that all
shadow dom ancestors are properly handled.
  • Loading branch information
breakthestatic authored Jan 9, 2023
1 parent 1dd42bb commit 7428761
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/isAttached.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
* Determine if an element is attached to the DOM
* Panzoom requires this so events work properly
*/
export default function isAttached(elem: HTMLElement | SVGElement | Document) {
const doc = elem.ownerDocument
const parent = elem.parentNode
return (
doc &&
parent &&
doc.nodeType === 9 &&
parent.nodeType === 1 &&
doc.documentElement.contains(parent)
)
export default function isAttached(node: Node) {
let currentNode = node
while (currentNode && currentNode.parentNode) {
if (currentNode.parentNode === document) return true
currentNode =
currentNode.parentNode instanceof ShadowRoot
? currentNode.parentNode.host
: currentNode.parentNode
}
return false
}
24 changes: 24 additions & 0 deletions test/unit/isAttached.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,30 @@ describe('isAttached', () => {
assert(isAttached(div))
document.body.removeChild(div)
})
it('determines if an attached shadow dom element is attached', () => {
const div = document.createElement('div')
const shadowChild = document.createElement('div')
div.attachShadow({ mode: 'open' }).appendChild(shadowChild)
document.body.appendChild(div)
assert(isAttached(shadowChild))
document.body.removeChild(div)
})
it('determines if a nested, attached shadow dom element is attached', () => {
const div = document.createElement('div')
const shadowChild = document.createElement('div')
const shadowGrandChild = document.createElement('div')
shadowChild.attachShadow({ mode: 'open' }).appendChild(shadowGrandChild)
div.attachShadow({ mode: 'open' }).appendChild(shadowChild)
document.body.appendChild(div)
assert(isAttached(shadowGrandChild))
document.body.removeChild(div)
})
it('determines if a detached shadow dom element is attached', () => {
const div = document.createElement('div')
const shadowChild = document.createElement('div')
div.attachShadow({ mode: 'open' }).appendChild(shadowChild)
assert(!isAttached(shadowChild))
})
it('determines if a detached element is attached', () => {
const div = document.createElement('div')
assert(!isAttached(div))
Expand Down

0 comments on commit 7428761

Please sign in to comment.