From c4761c1c5c9b32f801ef8ce6a8855bcd2f271bff Mon Sep 17 00:00:00 2001 From: wanhose Date: Tue, 29 Nov 2022 20:41:58 +0100 Subject: [PATCH] feat(browser-extension): improve viewport visibility check --- .../browser-extension/src/scripts/content.js | 41 ++++++++++++------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/packages/browser-extension/src/scripts/content.js b/packages/browser-extension/src/scripts/content.js index fb4de5a..fd4688f 100644 --- a/packages/browser-extension/src/scripts/content.js +++ b/packages/browser-extension/src/scripts/content.js @@ -78,6 +78,25 @@ const forceClean = () => { } }; +/** + * @description Checks if an element is visible in the viewport + * @param {HTMLElement} node + * @returns {boolean} + */ + +const isInViewport = (node) => { + const bounding = node.getBoundingClientRect(); + + return ( + bounding.top >= -node.offsetHeight && + bounding.left >= -node.offsetWidth && + bounding.right <= + (window.innerWidth || document.documentElement.clientWidth) + node.offsetWidth && + bounding.bottom <= + (window.innerHeight || document.documentElement.clientHeight) + node.offsetHeight + ); +}; + /** * @description Matches if node element is removable * @param {Element} node @@ -85,21 +104,13 @@ const forceClean = () => { * @returns {boolean} */ -const match = (node, skipMatch) => { - if (!(node instanceof HTMLElement)) return false; - - const rect = node.getBoundingClientRect(); - const isFullscreen = rect.bottom + rect.top > 0 && rect.bottom - rect.top === 0; - const isVisible = rect.top <= (window.innerHeight || document.documentElement.clientHeight); - - return ( - !data?.tags.includes(node.tagName?.toUpperCase?.()) && - (isFullscreen || isVisible) && - (node.offsetParent || window.getComputedStyle(node).position === 'fixed') && - node.parentElement && - (skipMatch || node.matches(data?.elements ?? [])) - ); -}; +const match = (node, skipMatch) => + node instanceof HTMLElement && + !data?.tags.includes(node.tagName?.toUpperCase?.()) && + isInViewport(node) && + (!!node.offsetParent || window.getComputedStyle(node).position === 'fixed') && + !!node.parentElement && + (skipMatch || node.matches(data?.elements ?? [])); /** * @description Fixes scroll issues