Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: Add support for querying shadow DOM #21233

Merged
merged 1 commit into from
Nov 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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('*')).find(el => el.shadowRoot);

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