Skip to content

Commit

Permalink
AG-34532 Improve 'trusted-click-element' scriptlet — fix click on pag…
Browse files Browse the repository at this point in the history
…e layout elements. #437
  • Loading branch information
jellizaveta committed Jul 23, 2024
1 parent 9b442f4 commit 6bc3ed5
Showing 1 changed file with 43 additions and 8 deletions.
51 changes: 43 additions & 8 deletions src/scriptlets/trusted-click-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,22 +383,57 @@ export function trustedClickElement(
}
};

const observer = new MutationObserver(throttle(findElements, THROTTLE_DELAY_MS));
observer.observe(document.documentElement, {
attributes: true,
childList: true,
subtree: true,
});
/**
* Initializes a `MutationObserver` to watch for changes in the DOM.
* The observer is set up to monitor changes in attributes, child nodes, and subtree.
* A timeout is set to disconnect the observer if no elements are found within the specified time.
*/
const initializeMutationObserver = () => {
const observer = new MutationObserver(throttle(findElements, THROTTLE_DELAY_MS));
observer.observe(document.documentElement, {
attributes: true,
childList: true,
subtree: true,
});

// Set timeout to disconnect observer if elements are not found within the specified time
setTimeout(() => observer.disconnect(), OBSERVER_TIMEOUT_MS);
};

/**
* Checks if elements are already present in the DOM.
* If elements are found, the observer is disconnected and the elements are clicked.
* If elements are not found, the observer is initialized.
*/
const checkInitialElements = () => {
const foundElements = selectorsSequence.some((selector) => {
if (!selector) {
return false;
}
const element = queryShadowSelector(selector);
return !!element;
});
if (foundElements) {
// Click previously collected elements and set canClick to true
findElements([], new MutationObserver(() => {}));
canClick = true;
} else {
// Initialize MutationObserver if elements were not found initially
initializeMutationObserver();
}
};

// Run the initial check
checkInitialElements();

// If there's a delay before clicking elements, use a timeout
if (parsedDelay) {
setTimeout(() => {
// Click previously collected elements
clickElementsBySequence();
canClick = true;
}, parsedDelay);
}

setTimeout(() => observer.disconnect(), OBSERVER_TIMEOUT_MS);
}

trustedClickElement.names = [
Expand Down

0 comments on commit 6bc3ed5

Please sign in to comment.