Skip to content

Commit 4d894de

Browse files
fix: hide tooltip when anchor is removed from DOM
1 parent 7dec4fc commit 4d894de

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/components/Tooltip/Tooltip.tsx

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,31 @@ const Tooltip = ({
263263
})
264264
})
265265

266+
const anchorElement = anchorById ?? activeAnchor.current
267+
268+
const parentObserverCallback: MutationCallback = (mutationList) => {
269+
if (!anchorElement) {
270+
return
271+
}
272+
mutationList.some((mutation) => {
273+
if (mutation.type !== 'childList') {
274+
return false
275+
}
276+
return [...mutation.removedNodes].some((node) => {
277+
if (node.contains(anchorElement)) {
278+
handleShow(false)
279+
return true
280+
}
281+
return false
282+
})
283+
})
284+
}
285+
286+
const parentObserver = new MutationObserver(parentObserverCallback)
287+
288+
// watch for anchor being removed from the DOM
289+
parentObserver.observe(document.body, { attributes: false, childList: true, subtree: true })
290+
266291
return () => {
267292
if (events.find((event: string) => event === 'click')) {
268293
window.removeEventListener('click', handleClickOutsideAnchor)
@@ -279,6 +304,7 @@ const Tooltip = ({
279304
ref.current?.removeEventListener(event, listener)
280305
})
281306
})
307+
parentObserver.disconnect()
282308
}
283309
}, [anchorRefs, activeAnchor, closeOnEsc, anchorId, events, delayHide, delayShow])
284310

0 commit comments

Comments
 (0)