Skip to content

Commit

Permalink
Refactor waitForClass function to handle page changes
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
HandyRandyx committed Aug 1, 2024
1 parent ca0567a commit 324536b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
3 changes: 3 additions & 0 deletions plugins/hotCards/hotCards.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
39 changes: 34 additions & 5 deletions plugins/hotCards/utils/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 324536b

Please sign in to comment.