Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix anchorsBySelect ref leak #1091

Merged
merged 6 commits into from
Oct 24, 2023
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions src/components/Tooltip/Tooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,10 @@ const Tooltip = ({
return
}

if (!activeAnchor?.isConnected) {
return
}

computeTooltipPosition({
place,
offset,
Expand Down Expand Up @@ -486,6 +490,7 @@ const Tooltip = ({
}
const documentObserverCallback: MutationCallback = (mutationList) => {
const newAnchors: HTMLElement[] = []
const removedAnchors: HTMLElement[] = []
mutationList.forEach((mutation) => {
if (mutation.type === 'attributes' && mutation.attributeName === 'data-tooltip-id') {
const newId = (mutation.target as HTMLElement).getAttribute('data-tooltip-id')
Expand All @@ -497,7 +502,23 @@ const Tooltip = ({
return
}
if (activeAnchor) {
;[...mutation.removedNodes].some((node) => {
const elements = [...mutation.removedNodes].filter((node) => node.nodeType === 1)
if (selector) {
removedAnchors.push(
// the element itself is an anchor
...(elements.filter((element) =>
(element as HTMLElement).matches(selector),
) as HTMLElement[]),
)
removedAnchors.push(
// the element has children which are anchors
...elements.flatMap(
(element) =>
[...(element as HTMLElement).querySelectorAll(selector)] as HTMLElement[],
),
)
}
elements.some((node) => {
if (node?.contains?.(activeAnchor)) {
setRendered(false)
handleShow(false)
Expand Down Expand Up @@ -538,8 +559,11 @@ const Tooltip = ({
*/
}
})
if (newAnchors.length) {
setAnchorsBySelect((anchors) => [...anchors, ...newAnchors])
if (newAnchors.length || removedAnchors.length) {
setAnchorsBySelect((anchors) => [
...anchors.filter((anchor) => removedAnchors.includes(anchor)),
...newAnchors,
])
}
}
const documentObserver = new MutationObserver(documentObserverCallback)
Expand Down
Loading