Extend body mutation observer

This adds missing mutation observer unregistration and extends it to
monitor host element resizes too.
This commit is contained in:
Simon Rozman 2024-06-26 08:51:39 +02:00
parent 393c372bbf
commit 042a6b288c

View File

@ -66,8 +66,12 @@ class BesService {
this.resizeObserver = new ResizeObserver(this.onResize.bind(this))
this.resizeObserver.observe(this.hostElement)
this.initialPosRect = this.hostElement.getBoundingClientRect()
this.initializePositionObserver()
this.hostBoundingClientRect = this.hostElement.getBoundingClientRect()
this.positionObserver = new MutationObserver(this.onBodyMutate.bind(this))
this.positionObserver.observe(document.body, {
childList: true,
subtree: true
})
besServices.push(this)
}
@ -101,6 +105,7 @@ class BesService {
unregister() {
if (this.abortController) this.abortController.abort()
besServices = besServices.filter(item => item !== this)
this.positionObserver.disconnect()
this.resizeObserver.disconnect()
this.hostElement.removeEventListener('scroll', this.onScroll)
this.hostElement.setAttribute('spellcheck', this.originalSpellcheck)
@ -239,6 +244,24 @@ class BesService {
this.repositionAllMarkup()
}
/**
* Called to report document body change
*/
onBodyMutate() {
const rect = this.hostElement.getBoundingClientRect()
if (
rect.top !== this.hostBoundingClientRect.top ||
rect.left !== this.hostBoundingClientRect.left
)
this.onReposition()
if (
rect.width !== this.hostBoundingClientRect.width ||
rect.height !== this.hostBoundingClientRect.height
)
this.onResize()
this.hostBoundingClientRect = rect
}
/**
* Creates grammar mistake markup in DOM.
*
@ -475,26 +498,6 @@ class BesService {
return false
}
}
/**
* Initializes position observer. This is necessary to monitor host element movements in DOM.
*/
initializePositionObserver() {
const positionObserver = new MutationObserver(() => {
const currentPosRect = this.hostElement.getBoundingClientRect()
if (
currentPosRect.top !== this.initialPosRect.top ||
currentPosRect.left !== this.initialPosRect.left
) {
this.onReposition()
this.initialPosRect = currentPosRect
}
})
positionObserver.observe(document.body, {
childList: true,
subtree: true
})
}
}
/**************************************************************************************************