@@ -359,7 +359,14 @@ const Tooltip = ({
359
359
selector = `[data-tooltip-id='${ id } ']`
360
360
}
361
361
const documentObserverCallback : MutationCallback = ( mutationList ) => {
362
+ const newAnchors : HTMLElement [ ] = [ ]
362
363
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
+ }
363
370
if ( mutation . type !== 'childList' ) {
364
371
return
365
372
}
@@ -379,26 +386,38 @@ const Tooltip = ({
379
386
}
380
387
try {
381
388
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
+ )
391
402
} catch {
392
403
/**
393
404
* invalid CSS selector.
394
405
* already warned on tooltip controller
395
406
*/
396
407
}
397
408
} )
409
+ if ( newAnchors . length ) {
410
+ setAnchorsBySelect ( ( anchors ) => [ ...anchors , ...newAnchors ] )
411
+ }
398
412
}
399
413
const documentObserver = new MutationObserver ( documentObserverCallback )
400
414
// 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
+ } )
402
421
return ( ) => {
403
422
documentObserver . disconnect ( )
404
423
}
0 commit comments