From 324536b605a7e3806d457a8c7cce98fc7a118114 Mon Sep 17 00:00:00 2001 From: HandyRandyx Date: Wed, 31 Jul 2024 21:28:22 -0300 Subject: [PATCH] Refactor waitForClass function to handle page changes There was a bug associated with this that happened when, for example, if we were in home and a user navigated to a gallery that had no performer or scene linked, when navigating backwards while waitForClass had not yet timed out, there would be a second waitForClass that would run, thus duplicating the hot-card elements. --- plugins/hotCards/hotCards.js | 3 +++ plugins/hotCards/utils/helpers.js | 39 +++++++++++++++++++++++++++---- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/plugins/hotCards/hotCards.js b/plugins/hotCards/hotCards.js index a4151798..9fa87e11 100644 --- a/plugins/hotCards/hotCards.js +++ b/plugins/hotCards/hotCards.js @@ -674,6 +674,9 @@ waitForImageLoad(targetEl, () => { const hotBorderEl = hotCardEl.querySelector(".hot-border"); + + if (!hotBorderEl) return; + const studioCardMarginSize = 5; const isSceneCard = cardClass === "scene-card"; const degreesOffset = isStudioCard ? 98 : isSceneCard ? 83 : 97; diff --git a/plugins/hotCards/utils/helpers.js b/plugins/hotCards/utils/helpers.js index b5c5339c..3ae8a945 100644 --- a/plugins/hotCards/utils/helpers.js +++ b/plugins/hotCards/utils/helpers.js @@ -14,20 +14,49 @@ function waitForClass(className, callback) { const checkInterval = 100; // ms const maxRetries = 30; // Timeout after 3 seconds let retryCount = 0; + let intervalId; - const intervalId = setInterval(() => { + function checkElements() { const elements = document.getElementsByClassName(className); if (elements.length > 0) { - clearInterval(intervalId); + clearAll(); callback(); } else if (retryCount >= maxRetries) { - clearInterval(intervalId); + clearAll(); console.info( - `Element with class ${className} not found within timeout period` + `Element with class "${className}" not found within timeout period` ); } retryCount++; - }, checkInterval); + } + + function clearAll() { + clearInterval(intervalId); + removeEventListeners(); + } + + function clear() { + console.info( + `Element with class "${className}" search cancelled due to page change` + ); + clearAll(); + } + + function addEventListeners() { + document.addEventListener("visibilitychange", clear); + window.addEventListener("beforeunload", clear); + window.addEventListener("popstate", clear); + } + + function removeEventListeners() { + document.removeEventListener("visibilitychange", clear); + window.removeEventListener("beforeunload", clear); + window.removeEventListener("popstate", clear); + } + + // Start the interval and add event listeners + intervalId = setInterval(checkElements, checkInterval); + addEventListeners(); } function waitForImageLoad(imageEl, callback) {