Skip to content

Commit

Permalink
Merge pull request #125 from UrbanInstitute/fix-tooltip-shadow-dom
Browse files Browse the repository at this point in the history
Fix: tooltip position inside shadow root
  • Loading branch information
mitchthorson authored Dec 31, 2024
2 parents d8b6867 + 9aedfca commit eb4fe79
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# @UrbanInstitute/dataviz-components Changelog

## Next
- Fix: Tooltip positioning works as expected when inside a ShadowRoot of a custom element

## v0.12.3
- Fix: Tooltip checks if ancestor is an instance of Element before calling getComputedStyle
Expand Down
25 changes: 20 additions & 5 deletions src/lib/Tooltip/Tooltip.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,27 @@
if (!el) return;
// traverse the tree upwards to see if there are any absolutely, fixed or relatively positioned ancestors
let ancestor = el.parentNode;
while (ancestor && ancestor !== document.documentElement && ancestor instanceof Element) {
const position = window.getComputedStyle(ancestor).position;
if (position === "relative" || position === "absolute" || position === "fixed") {
return ancestor;
// loop through all ancestors until we reach the document element
while (ancestor && ancestor !== document.documentElement) {
// check if ancestor is a shadow root with a host element
if (ancestor instanceof ShadowRoot) {
// if it is, set ancestor to the host element instead
ancestor = ancestor.host;
}
// make sure ancestor is instance of element
if (ancestor instanceof Element) {
// if it is, check if it is relative, absolute or fixed position
const position = window.getComputedStyle(ancestor).position;
// return it if so
if (position === "relative" || position === "absolute" || position === "fixed") {
return ancestor;
}
// check next ancestor
ancestor = ancestor.parentNode;
} else {
// if ancestor is not an element, break the loop
break;
}
ancestor = ancestor.parentNode;
}
return null;
}
Expand Down

0 comments on commit eb4fe79

Please sign in to comment.