Skip to content

Commit

Permalink
test: Add support for querying shadow DOM
Browse files Browse the repository at this point in the history
Add a `querySelectorAll()` variant which can transparently pierce and
traverse shadow DOMs without having to know their structure (i.e. doing
selectors piece-wise and iterating on their `.shadowRoot` attribute).

As this is more expensive than standard querySelector()`, only  use it
if the page actually contains any shadow root.

This makes it a lot more convenient to write tests for pages which use
web components, like https://patternflyelements.org.
  • Loading branch information
martinpitt committed Nov 16, 2024
1 parent a5c3cf2 commit 0b38c3f
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions test/common/test-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,38 @@
* These are routines used by our testing code.
*/

/* Detect if we have any shadow DOM */
window.__haveShadowDom = function() {
if (window.__haveShadowDomResult === undefined)
window.__haveShadowDomResult = Array.from(document.querySelectorAll('*')).filter(el => el.shadowRoot).length > 0;

return window.__haveShadowDomResult;
};

// Like querySelectorAll(), but traverses shadow DOM
window.querySelectorAllDeep = function(query, element) {
const result = Array.from(
element.shadowRoot
? element.shadowRoot.childNodes
: element.nodeName === 'SLOT' ? element.assignedElements() : element.childNodes,
)
.filter(element => element instanceof Element)
.map(element => window.querySelectorAllDeep(query, element))
.flat();

if (element.matches?.(query))
result.push(element);
return result;
};

window.ph_select = function(sel) {
if (sel.includes(":contains(")) {
if (!window.Sizzle) {
throw new Error("Using ':contains' when window.Sizzle is not available.");
}
return window.Sizzle(sel);
} else if (window.__haveShadowDom()) {
return window.querySelectorAllDeep(sel, document);
} else {
return Array.from(document.querySelectorAll(sel));
}
Expand Down

0 comments on commit 0b38c3f

Please sign in to comment.