From 042a6b288c5b90f9292902c570e1db37ebac9c72 Mon Sep 17 00:00:00 2001 From: Simon Rozman Date: Wed, 26 Jun 2024 08:51:39 +0200 Subject: [PATCH] Extend body mutation observer This adds missing mutation observer unregistration and extends it to monitor host element resizes too. --- service.js | 47 +++++++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/service.js b/service.js index fae2d39..246d2f9 100644 --- a/service.js +++ b/service.js @@ -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 - }) - } } /**************************************************************************************************