Skip to content

Commit 33170c0

Browse files
fix: watch for attribute changes
1 parent 0b894a4 commit 33170c0

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

Diff for: src/components/Tooltip/Tooltip.tsx

+29-10
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,14 @@ const Tooltip = ({
359359
selector = `[data-tooltip-id='${id}']`
360360
}
361361
const documentObserverCallback: MutationCallback = (mutationList) => {
362+
const newAnchors: HTMLElement[] = []
362363
mutationList.forEach((mutation) => {
364+
if (mutation.type === 'attributes' && mutation.attributeName === 'data-tooltip-id') {
365+
const newId = (mutation.target as HTMLElement).getAttribute('data-tooltip-id')
366+
if (newId === id) {
367+
newAnchors.push(mutation.target as HTMLElement)
368+
}
369+
}
363370
if (mutation.type !== 'childList') {
364371
return
365372
}
@@ -379,26 +386,38 @@ const Tooltip = ({
379386
}
380387
try {
381388
const elements = [...mutation.addedNodes].filter((node) => node.nodeType === 1)
382-
const newAnchors = [
383-
...elements.filter((element) => (element as HTMLElement).matches(selector)),
384-
...elements.flatMap((element) => [
385-
...(element as HTMLElement).querySelectorAll(selector),
386-
]),
387-
] as HTMLElement[]
388-
if (newAnchors.length) {
389-
setAnchorsBySelect((anchors) => [...anchors, ...newAnchors])
390-
}
389+
newAnchors.push(
390+
// the element itself is an anchor
391+
...(elements.filter((element) =>
392+
(element as HTMLElement).matches(selector),
393+
) as HTMLElement[]),
394+
)
395+
newAnchors.push(
396+
// the element has children which are anchors
397+
...elements.flatMap(
398+
(element) =>
399+
[...(element as HTMLElement).querySelectorAll(selector)] as HTMLElement[],
400+
),
401+
)
391402
} catch {
392403
/**
393404
* invalid CSS selector.
394405
* already warned on tooltip controller
395406
*/
396407
}
397408
})
409+
if (newAnchors.length) {
410+
setAnchorsBySelect((anchors) => [...anchors, ...newAnchors])
411+
}
398412
}
399413
const documentObserver = new MutationObserver(documentObserverCallback)
400414
// watch for anchor being removed from the DOM
401-
documentObserver.observe(document.body, { attributes: false, childList: true, subtree: true })
415+
documentObserver.observe(document.body, {
416+
childList: true,
417+
subtree: true,
418+
attributes: true,
419+
attributeFilter: ['data-tooltip-id'],
420+
})
402421
return () => {
403422
documentObserver.disconnect()
404423
}

0 commit comments

Comments
 (0)