diff --git a/docs-site/src/content/docs/api/E2E/TextMatchOptions.md b/docs-site/src/content/docs/api/E2E/TextMatchOptions.md
index 26abf1ecd..f9db27c26 100644
--- a/docs-site/src/content/docs/api/E2E/TextMatchOptions.md
+++ b/docs-site/src/content/docs/api/E2E/TextMatchOptions.md
@@ -59,8 +59,14 @@ Drops nodes the platform reports as hidden before the exactly-one rule,
so a visible node with a hidden twin still resolves. On the web, hidden is
what renders: `display: none`, a `visibility` other than
`visible`, and content under `content-visibility: hidden` or a
-closed `details`; a child that sets `visibility: visible` under a
-hidden parent is visible, and an `aria-hidden` node that paints is visible.
+closed `details` body (all but its first `summary`), shadow and slotted content included; a child that sets
+`visibility: visible` under a hidden parent is visible, and an
+`aria-hidden` node that paints is visible. A closed `details` body
+the page's CSS shows through `::details-content` is not hidden, and neither
+is content under `content-visibility: hidden` set on an element whose box
+skips nothing (`display: contents`, an inline element, a table, a table row,
+ruby). An outermost inline `svg` (not one nested in another),
+`button`, or `fieldset` makes a box of its own, so content under one still reads hidden.
Everything inside a hidden `iframe` is hidden, cross-origin frames included.
Role queries never match hidden or `aria-hidden` nodes, whatever this says.
diff --git a/skills/e2e-dotnet/references/writing-tests.md b/skills/e2e-dotnet/references/writing-tests.md
index ac06c0dd8..0c96efd27 100644
--- a/skills/e2e-dotnet/references/writing-tests.md
+++ b/skills/e2e-dotnet/references/writing-tests.md
@@ -233,7 +233,11 @@ Members of `E2ETest` in both frameworks:
page hides (a closed drawer) before the exactly-one rule. Visibility is
what renders, as `ToBeVisibleAsync` reads it: `display: none`, a
`visibility` other than `visible`, and content under
- `content-visibility: hidden` or a closed `details` are hidden. A child that
+ `content-visibility: hidden` or a closed `details` body (all but its first
+ `summary`) are hidden, through shadow
+ roots and slots too, unless the page's CSS still shows them (a closed
+ `details` body through `::details-content`, `content-visibility: hidden` on an
+ element whose box skips nothing). A child that
sets `visibility: visible` under a hidden parent is visible, and a
`display: contents` element is visible when something under it is. An
`aria-hidden` node that paints is visible, as upstream, but the tree leaves
diff --git a/src/E2E/Engine/PageScript.cs b/src/E2E/Engine/PageScript.cs
index b4dbecdd1..5872fb5c5 100644
--- a/src/E2E/Engine/PageScript.cs
+++ b/src/E2E/Engine/PageScript.cs
@@ -210,19 +210,6 @@ internal static class PageScript
}
return found;
};
- // Upstream's slotOf: assignedSlot, else the tracked closed root's own slots.
- const slotOf = (el) => {
- if (el.assignedSlot !== null) return el.assignedSlot;
- const host = el.parentElement;
- const shadow = host === null ? undefined : closedRoots?.get(host);
- if (shadow === undefined) return null;
- for (const slot of Array.from(shadow.querySelectorAll("slot"))) {
- if (slot.assignedElements().indexOf(el) !== -1) return slot;
- }
- return null;
- };
- // Upstream's flatParentOf: an element's parent in the flat tree.
- const flatParentOf = memoized((el) => slotOf(el) ?? parentOrHostOf(el));
const isInFlatTree = (el, container) => {
for (let current = el; current !== null; current = flatParentOf(current)) {
if (current === container) return true;
@@ -276,7 +263,7 @@ internal static class PageScript
if (el.tagName === "IFRAME" && (ariaHidden(el) || hidden(el))) return 0;
let n = 0;
const style = getComputedStyle(el);
- const isHidden = !!parentHidden || hidden(el, style);
+ const isHidden = !!parentHidden || hidden(el, style) || hiddenAbove(el);
// Upstream returns at a hidden select, so its options are neither listed nor counted.
if (isHidden && el.tagName === "SELECT") return 0;
const childrenHidden = !!parentHidden || hidesSubtree(el, style);
@@ -298,6 +285,8 @@ internal static class PageScript
return n + offered;
}
}
+ // The element keeps its box, and nothing under it renders (skipsContents), so nothing under it is counted.
+ if (skipsContents(el, style)) return n;
for (const child of el.children) n += tally(child, visible, childrenHidden);
const shadow = shadowOf(el);
if (shadow) for (const child of shadow.children) n += tally(child, visible, childrenHidden);
@@ -312,7 +301,7 @@ internal static class PageScript
const place = modal === undefined ? "inside" : modal.placeOf(el);
if (place === "outside") return;
const style = getComputedStyle(el);
- const isHidden = !!parentHidden || hidden(el, style);
+ const isHidden = !!parentHidden || hidden(el, style) || hiddenAbove(el);
const childrenHidden = !!parentHidden || hidesSubtree(el, style);
const role = roleOf(el);
const isFrame = el.tagName === "IFRAME";
@@ -383,6 +372,8 @@ internal static class PageScript
// light children and the shadow tree holds only their slots, so
// nothing is listed twice.
const walkChildren = (el, into, parentHidden) => {
+ // The element keeps its box, and nothing under it renders (skipsContents), so the walk stops at it.
+ if (skipsContents(el, styleOf(el))) return;
for (const child of el.children) walk(child, into, parentHidden);
const shadow = shadowOf(el);
if (shadow) for (const child of shadow.children) walk(child, into, parentHidden);
diff --git a/src/E2E/Engine/ReadSemantics.cs b/src/E2E/Engine/ReadSemantics.cs
index 3891383cd..4b61512b6 100644
--- a/src/E2E/Engine/ReadSemantics.cs
+++ b/src/E2E/Engine/ReadSemantics.cs
@@ -67,17 +67,82 @@ internal static class ReadSemantics
const text = (value || "").replace(/\s+/g, " ").trim();
return text.length > limit ? text.slice(0, limit) : text;
};
- // Content a closed details folds away: anything under it outside its
- // summary. Every closed ancestor is asked, nested details included.
- const inClosedDetails = (el) => {
- for (let details = el.parentElement?.closest("details"); details; details = details.parentElement?.closest("details")) {
- if (!details.open) {
- const summary = details.querySelector(":scope > summary");
- if (!summary || !summary.contains(el)) return true;
+ // Upstream's BOXES_THAT_SKIP_NOTHING: display values on which content-visibility: hidden skips nothing (checked against
+ // checkVisibility() in Chromium).
+ const BOXES_THAT_SKIP_NOTHING = new Set(["contents", "inline", "inline list-item", "table", "inline-table", "table-row", "table-row-group", "table-header-group", "table-footer-group", "ruby", "ruby-text"]);
+ // Upstream's isHtml: an HTML element; an SVG slot or a foreign summary does nothing.
+ const isHtml = (node) => node.namespaceURI === "http://www.w3.org/1999/xhtml";
+ // Upstream's skipsContents: whether an element with this style renders nothing under it. In SVG only an outermost svg, one whose
+ // parent is not SVG or is a foreignObject, has a box for content-visibility to act on, and as a replaced element it skips whatever
+ // its display. An HTML button or fieldset also makes a box of its own short of display: contents.
+ const skipsContents = (el, style) => {
+ if (style?.getPropertyValue("content-visibility") !== "hidden") return false;
+ const svg = "http://www.w3.org/2000/svg";
+ if (el.namespaceURI === svg) return el.localName === "svg" && (el.parentElement?.namespaceURI !== svg || el.parentElement.localName === "foreignObject");
+ if (!BOXES_THAT_SKIP_NOTHING.has(style.display)) return true;
+ return (el.localName === "button" || el.localName === "fieldset") && el.namespaceURI === "http://www.w3.org/1999/xhtml" && style.display !== "contents";
+ };
+ // Upstream's closedSlots: a tracked closed root's HTML slots, read once per root in a read: by name, the first slot of each name in
+ // tree order, as named assignment picks it; in a root that assigns by hand, by each element a slot holds. A named lookup never lists
+ // what a slot holds, so a locator's read of one match costs one pass over the root's slots.
+ const closedSlots = new Map();
+ // Upstream's slotOf: assignedSlot, which a closed root hides from the outside, else the tracked closed root's slot for the element.
+ const slotOf = (el) => {
+ if (el.assignedSlot !== null) return el.assignedSlot;
+ const host = el.parentElement;
+ const shadow = host === null ? undefined : closedRoots?.get(host);
+ if (shadow === undefined) return null;
+ const manual = shadow.slotAssignment === "manual";
+ let slots = closedSlots.get(shadow);
+ if (slots === undefined) {
+ slots = new Map();
+ for (const slot of Array.from(shadow.querySelectorAll("slot"))) {
+ if (!isHtml(slot)) continue;
+ if (manual) {
+ for (const assigned of slot.assignedElements()) slots.set(assigned, slot);
+ continue;
+ }
+ const name = slot.getAttributeNS(null, "name") ?? "";
+ if (!slots.has(name)) slots.set(name, slot);
}
+ closedSlots.set(shadow, slots);
}
- return false;
+ return slots.get(manual ? el : (el.getAttributeNS(null, "slot") ?? "")) ?? null;
};
+ // Upstream's flatParentOf: an element's parent in the flat tree: its slot, the tree parent, or the host at a shadow root.
+ const flatParentOf = memoized((el) => slotOf(el) ?? parentOrHostOf(el));
+ // Upstream's firstSummaryOf: a details element's summary, its first HTML summary child.
+ const firstSummaryOf = memoized((details) => {
+ // One read of the children, not a step per sibling, so a wide details costs one pass for the whole read.
+ for (const child of details.children) {
+ if (child.localName === "summary" && isHtml(child)) return child;
+ }
+ return null;
+ });
+ // Upstream's foldsBody: whether a details element hides its body: its ::details-content skips its contents (skipsContents), so page
+ // CSS can show a closed body. Without that pseudo element, the open attribute decides.
+ const foldsBody = memoized((details) => {
+ const style = details.ownerDocument.defaultView?.getComputedStyle(details, "::details-content");
+ const skip = style?.getPropertyValue("content-visibility") ?? "";
+ return skip === "" ? !details.hasAttribute("open") : skipsContents(details, style);
+ });
+ // Upstream's isInClosedDetails: content a closed details folds away: anything under it in the flat tree, slotted and shadow content
+ // included, outside its summary. Every details on the way up is asked. Known by name, not instanceof, so one adopted from another
+ // frame still counts.
+ const isInClosedDetails = memoized((el) => {
+ const parent = flatParentOf(el);
+ if (parent === null) return false;
+ if (parent.localName === "details" && isHtml(parent) && foldsBody(parent) && firstSummaryOf(parent) !== el) return true;
+ return isInClosedDetails(parent);
+ });
+ // Whether an element hides its subtree for the walk: display: none, which no descendant can undo, or content it skips.
+ // Port only: the ancestors of one element, read up the flat tree and kept once per element.
+ const hiddenAbove = memoized((el) => {
+ const parent = flatParentOf(el);
+ if (parent === null) return false;
+ const style = styleOf(parent);
+ return style.display === "none" || skipsContents(parent, style) || hiddenAbove(parent);
+ });
// A text node that lays out to a box a person can see.
const visibleText = (node) => {
const range = document.createRange();
@@ -103,7 +168,7 @@ internal static class ReadSemantics
}
return true;
}
- return style.display === "none" || style.visibility !== "visible" || inClosedDetails(el);
+ return style.display === "none" || style.visibility !== "visible" || isInClosedDetails(el);
};
const ariaHidden = (el) => (el.getAttribute("aria-hidden") || "").toLowerCase() === "true";
// What stops the element and everything under it from rendering:
@@ -113,7 +178,7 @@ internal static class ReadSemantics
// visible and paint again; nor is aria-hidden, which only the
// accessibility tree drops. A closed details body is in it too: no
// descendant can undo the fold.
- const hidesSubtree = (el, style) => style.display === "none" || style.contentVisibility === "hidden" || inClosedDetails(el);
+ const hidesSubtree = (el, style) => style.display === "none" || skipsContents(el, style) || isInClosedDetails(el);
// Port only: upstream has no paragraph role, so it needs no test for content inside a host.
const inEditingHost = (el) => {
if (el.parentElement?.closest("[contenteditable]") == null) return false;
@@ -234,7 +299,7 @@ internal static class ReadSemantics
const isVisibleEmptyBox = memoized((el) => {
const style = styleOf(el);
if (style === undefined) return false;
- if (el.children.length > 0) return false;
+ if (el.childElementCount > 0) return false;
const explicit = (el.getAttribute("role") ?? "").trim();
if (explicit !== "") return false;
if (directTextOf(el) !== "") return false;
@@ -243,7 +308,8 @@ internal static class ReadSemantics
return hasPaint(style);
});
const tagRole = (el) => {
- const tag = el.tagName;
+ // Read by name whatever the namespace, as upstream lowercases tagName: an element a page adds in another namespace is still a button.
+ const tag = el.tagName.toUpperCase();
switch (tag) {
case "A": return el.hasAttribute("href") ? "link" : null;
case "BUTTON": return "button";
@@ -255,7 +321,7 @@ internal static class ReadSemantics
: "image";
// An inline icon is a picture whether or not anything names it, as
// Playwright reads it; Chrome ignores an unnamed one.
- case "svg": return "image";
+ case "SVG": return "image";
case "NAV": return "navigation";
case "MAIN": return "main";
case "ASIDE": return "complementary";
@@ -396,10 +462,10 @@ internal static class ReadSemantics
if (!style) styles.set(el, style = getComputedStyle(el));
return style;
};
- // Text owned directly by an element, excluding descendant elements. An element with content-visibility: hidden renders none of
- // it, as its innerText reads empty, so it owns none.
+ // Text owned directly by an element, excluding descendant elements. An element that skips its contents (skipsContents) renders none
+ // of it, as its innerText reads empty, so it owns none.
const directTextOf = memoized((el) => {
- if (styleOf(el)?.getPropertyValue("content-visibility") === "hidden") return "";
+ if (skipsContents(el, styleOf(el))) return "";
let out = "";
for (const child of Array.from(el.childNodes)) {
if (child.nodeType === 3) out += child.nodeValue ?? "";
@@ -855,7 +921,7 @@ internal static class ReadSemantics
///
public const string HiddenMode = """
const shownInTree = (el) => {
- for (let parent = parentOrHostOf(el); parent !== null; parent = parentOrHostOf(parent)) {
+ for (let parent = flatParentOf(el); parent !== null; parent = flatParentOf(parent)) {
if (hidesSubtree(parent, getComputedStyle(parent))) return false;
}
if (hidden(el)) return false;
@@ -870,8 +936,8 @@ internal static class ReadSemantics
const isDrawnByLabel = (el, style) => {
if (!(el instanceof HTMLInputElement) || (el.type !== "checkbox" && el.type !== "radio")) return false;
if (style.visibility !== "visible") return false;
- // A slotted element is skipped with the slot it renders in (upstream's isSkippedContent reads assignedSlot first).
- for (let parent = el.assignedSlot ?? parentOrHostOf(el); parent !== null; parent = parent.assignedSlot ?? parentOrHostOf(parent)) {
+ // A slotted element is skipped with the slot it renders in (upstream's isSkippedContent steps with flatParentOf).
+ for (let parent = flatParentOf(el); parent !== null; parent = flatParentOf(parent)) {
if (hidesSubtree(parent, getComputedStyle(parent))) return false;
}
const INTERACTIVE = 'a,button,input,select,textarea,summary,[contenteditable],[role="button"],[role="link"]';
@@ -972,7 +1038,7 @@ internal static class ReadSemantics
// walk carries down.
const nodeOf = (el, testIdAttribute) => {
let isHidden = false;
- for (let parent = parentOrHostOf(el); parent !== null; parent = parentOrHostOf(parent)) {
+ for (let parent = flatParentOf(el); parent !== null; parent = flatParentOf(parent)) {
if (hidesSubtree(parent, getComputedStyle(parent))) isHidden = true;
}
return fieldsOf(el, roleOf(el), {
diff --git a/src/E2E/Engine/ShownSelector.cs b/src/E2E/Engine/ShownSelector.cs
index d517c9480..78a0da877 100644
--- a/src/E2E/Engine/ShownSelector.cs
+++ b/src/E2E/Engine/ShownSelector.cs
@@ -25,9 +25,14 @@ internal static class ShownSelector
///
public static readonly string ShownSelectorEngineSource = $$"""
() => {
+ // A reader of its own for each query, as upstream calls the reader once per read: its memo caches hold computed styles and
+ // the flat tree, which would go stale between two queries of an engine that lives as long as the document.
+ const readerOf = () => {
{{ReadSemantics.Prelude}}
{{ReadSemantics.HiddenMode}}
- const queryAll = (root) => (root.nodeType === 1 && shownInTree(root) ? [root] : []);
+ return shownInTree;
+ };
+ const queryAll = (root) => (root.nodeType === 1 && readerOf()(root) ? [root] : []);
return { queryAll, query: (root) => queryAll(root)[0] ?? null };
}
""";
diff --git a/src/E2E/Locator/TextMatch.cs b/src/E2E/Locator/TextMatch.cs
index d821d5186..de2dd8181 100644
--- a/src/E2E/Locator/TextMatch.cs
+++ b/src/E2E/Locator/TextMatch.cs
@@ -126,8 +126,14 @@ public class TextMatchOptions
/// so a visible node with a hidden twin still resolves. On the web, hidden is
/// what renders: display: none, a visibility other than
/// visible, and content under content-visibility: hidden or a
- /// closed details; a child that sets visibility: visible under a
- /// hidden parent is visible, and an aria-hidden node that paints is visible.
+ /// closed details body (all but its first summary), shadow and slotted content included; a child that sets
+ /// visibility: visible under a hidden parent is visible, and an
+ /// aria-hidden node that paints is visible. A closed details body
+ /// the page's CSS shows through ::details-content is not hidden, and neither
+ /// is content under content-visibility: hidden set on an element whose box
+ /// skips nothing (display: contents, an inline element, a table, a table row,
+ /// ruby). An outermost inline svg (not one nested in another),
+ /// button, or fieldset makes a box of its own, so content under one still reads hidden.
/// Everything inside a hidden iframe is hidden, cross-origin frames included.
/// Role queries never match hidden or aria-hidden nodes, whatever this says.
///
diff --git a/tests/E2E.Tests/ChromiumPage.cs b/tests/E2E.Tests/ChromiumPage.cs
index 518831a78..d86cb22fb 100644
--- a/tests/E2E.Tests/ChromiumPage.cs
+++ b/tests/E2E.Tests/ChromiumPage.cs
@@ -43,6 +43,31 @@ public async Task InitializeAsync()
await Page.GotoAsync("about:blank");
}
+ ///
+ /// A page of its own in the same browser, with the closed-root record, as the engine's context opens one. A test that defines custom
+ /// elements needs one, since a registry outlives SetContentAsync on the class page.
+ ///
+ public async Task NewPageAsync()
+ {
+ var page = await _browser!.NewPageAsync(
+ new BrowserNewPageOptions
+ {
+ ViewportSize = new ViewportSize { Width = 1280, Height = 720 },
+ }
+ );
+ try
+ {
+ await page.AddInitScriptAsync(PageScript.RecordClosedShadowRoots);
+ await page.GotoAsync("about:blank");
+ return page;
+ }
+ catch
+ {
+ await page.CloseAsync();
+ throw;
+ }
+ }
+
public async Task DisposeAsync()
{
if (_browser is not null)
@@ -57,10 +82,10 @@ public async Task DisposeAsync()
/// The port's reader over the page: every node it lists, in document order. is the
/// most nodes the walk counts, as upstream's capture takes it.
///
- public async Task> CaptureAsync(int budget = ObservationLimits.Nodes)
+ public async Task> CaptureAsync(int budget = ObservationLimits.Nodes, IPage? on = null)
{
// The next free ref carries over, as the engine's does, so a ref never names two elements.
- var observed = await Page.EvaluateAsync(
+ var observed = await (on ?? Page).EvaluateAsync(
PageScript.Collect,
new
{
diff --git a/tests/E2E.Tests/Crosscheck/CrosscheckFixtures.cs b/tests/E2E.Tests/Crosscheck/CrosscheckFixtures.cs
index 41e4c6a7b..0726bb864 100644
--- a/tests/E2E.Tests/Crosscheck/CrosscheckFixtures.cs
+++ b/tests/E2E.Tests/Crosscheck/CrosscheckFixtures.cs
@@ -416,6 +416,55 @@ public static class CrosscheckFixtures
"""
),
+ new(
+ "closed details and skipped content across shadow boundaries",
+ """
+ Shadow details
+
+
+
+
+
+ """
+ ),
+ new(
+ "content-visibility on boxes that skip nothing and boxes of their own",
+ """
+
+ Laid out
+
Column
+
+
+
+
+
+
+
+
+ """
+ ),
new(
"list rebuilt every millisecond",
"""
diff --git a/tests/E2E.Tests/Crosscheck/expected.txt b/tests/E2E.Tests/Crosscheck/expected.txt
index ce7c9f854..b8d79949f 100644
--- a/tests/E2E.Tests/Crosscheck/expected.txt
+++ b/tests/E2E.Tests/Crosscheck/expected.txt
@@ -2,6 +2,9 @@
# page | oracle field | role "name" | ours | theirs | reason
# Generated by E2E_CROSSCHECK_UPDATE=1; edit only the reasons. See tests/E2E.Tests/Crosscheck/CrosscheckExpectations.cs.
benchmark: file-round-trip | chrome name | button "" | ours | theirs Choose File | An unlabeled file input shows the browser's localized button text, which the page cannot read; Playwright reports it too, the tree leaves the input unnamed rather than guess the locale
+fixture: content-visibility on boxes that skip nothing and boxes of their own | chrome role | cell "Slotted in closed table" | ours cell | theirs LayoutTableCell | Chrome exposes a table under `content-visibility: hidden` as a layout table, a role a person never names; the tree reads the table, row and cell by their tags, as upstream does
+fixture: content-visibility on boxes that skip nothing and boxes of their own | chrome role | row "Slotted in closed table" | ours row | theirs LayoutTableRow | Chrome exposes a table under `content-visibility: hidden` as a layout table, a role a person never names; the tree reads the table, row and cell by their tags, as upstream does
+fixture: content-visibility on boxes that skip nothing and boxes of their own | chrome role | table "" | ours table | theirs LayoutTable | Chrome exposes a table under `content-visibility: hidden` as a layout table, a role a person never names; the tree reads the table, row and cell by their tags, as upstream does
fixture: controls drawn by their label | chrome missing | checkbox "" | ours no node | theirs checkbox | A checkbox with no box whose only label is not rendered shows a person nothing to aim at; the tree lists one only while a label of its own draws it
fixture: controls drawn by their label | chrome missing | checkbox "Accept the terms" | ours no node | theirs checkbox | A tap on a checkbox with no box clicks its label, which it refuses when the label's centre lands on a link, so the click follows no link; the tree leaves the checkbox out when its label holds a link anywhere, a stricter rule, rather than list one a tap may not reach
fixture: controls drawn by their label | chrome missing | checkbox "Contents" | ours no node | theirs checkbox | A `display: contents` label has no box, so a tap cannot click it in place of a checkbox with no box; the tree leaves the checkbox out and the model taps the label text, which sets it
diff --git a/tests/E2E.Tests/VisibilityShadow/VisibilityAcrossShadowBoundariesInTheFlatTreeTests.cs b/tests/E2E.Tests/VisibilityShadow/VisibilityAcrossShadowBoundariesInTheFlatTreeTests.cs
new file mode 100644
index 000000000..ee43b6a9d
--- /dev/null
+++ b/tests/E2E.Tests/VisibilityShadow/VisibilityAcrossShadowBoundariesInTheFlatTreeTests.cs
@@ -0,0 +1,580 @@
+// Copyright 2026 TesterArmy.
+// Modified by Dario Kondratiuk.
+// SPDX-License-Identifier: Apache-2.0
+
+using E2E.Engine;
+using Microsoft.Playwright;
+
+namespace E2E.Tests.VisibilityShadow;
+
+///
+/// The reader's hidden state across shadow boundaries, which isVisible(), toBeVisible(), and toBeHidden() read:
+/// content a closed <details> folds away and content under content-visibility: hidden are hidden in the flat tree, so a
+/// shadow tree under a closed <details> and an element slotted into one, or into a closed root, read hidden the way Playwright
+/// reads them. The agent's tree leaves the same buttons out. Upstream's describe('visibility across shadow boundaries, in the flat tree').
+///
+[Collection(BrowserCollection.Name)]
+public sealed class VisibilityAcrossShadowBoundariesInTheFlatTreeTests(ChromiumPage chromium)
+ : IClassFixture,
+ IAsyncLifetime
+{
+ private readonly List _pages = [];
+
+ private const string Html = """
+ Light
+ Shadow
+
+
+
+ body
+ Open
+
+
+
+
+ First
+
+
+
+
+
+
+
+
+ CSS accordion
+
+
+
+
+
+
+
+
+
Loose text under a box-less wrapper
+
+ Laid out
+
+
+
+
+
+
+
+
+
+
+
+ Foreign object svg link
+ Inner block svg link
+
+
+
+
+ """;
+
+ public Task InitializeAsync() => Task.CompletedTask;
+
+ public async Task DisposeAsync()
+ {
+ foreach (var page in _pages)
+ {
+ await page.CloseAsync();
+ }
+ }
+
+ // Upstream opens the page once in beforeAll; custom elements cannot be defined twice on one, so each test opens its own.
+ private async Task SetUpAsync()
+ {
+ var page = await OtherPageAsync();
+ await page.SetContentAsync(Html);
+ return page;
+ }
+
+ // Upstream's hiddenOf: the reader's hidden state for the selector on a page, next to what Playwright says of the same element.
+ private async Task<(bool Reader, bool Playwright)> HiddenOfAsync(IPage on, string selector)
+ {
+ var locator = on.Locator(selector);
+ var read = await chromium.ReadAsync(locator);
+ return (read!.Hidden, await locator.IsHiddenAsync());
+ }
+
+ // A page of its own with the closed-root record, as the engine's context opens one.
+ private async Task OtherPageAsync()
+ {
+ var page = await chromium.NewPageAsync();
+ _pages.Add(page);
+ return page;
+ }
+
+ [Theory]
+ [InlineData("a light button under closed details", "#light-in-closed", true)]
+ [InlineData("a shadow button under closed details", "#shadow-in-closed", true)]
+ [InlineData("a button slotted into closed details in an open root", "#slotted", true)]
+ [InlineData("a button slotted into closed details in a closed root", "#slotted-closed", true)]
+ [InlineData("a button slotted into the summary of closed details", "#in-summary-slot", false)]
+ [InlineData("a button slotted into the body of closed details", "#in-body-slot", true)]
+ [InlineData("a shadow button in the summary of closed details", "#shadow-in-summary", false)]
+ [InlineData("a shadow button under open details", "#shadow-in-open", false)]
+ [InlineData("a button slotted under content-visibility: hidden in a closed root", "#cv-closed", true)]
+ [InlineData("a button slotted under content-visibility: hidden in an open root", "#cv-open", true)]
+ [InlineData(
+ "a button slotted by name into the summary of closed details in a closed root",
+ "#closed-summary-slot",
+ false
+ )]
+ [InlineData("a button slotted into the body of closed details in a closed root", "#closed-body-slot", true)]
+ [InlineData(
+ "a button assigned by hand into the summary of closed details in a closed root",
+ "#manual-summary",
+ false
+ )]
+ [InlineData("a button assigned by hand into the body of closed details in a closed root", "#manual-body", true)]
+ [InlineData("a button in a second summary of closed details", "#second-summary", true)]
+ [InlineData("a button in a summary that is not a child of closed details", "#nested-summary", true)]
+ [InlineData("a button in the first child summary of closed details, after a nested one", "#direct-summary", false)]
+ [InlineData(
+ "a button slotted into an HTML slot of a closed root, past an SVG element named slot under closed details",
+ "#svg-named",
+ false
+ )]
+ [InlineData(
+ "a button slotted into the first of two slots of its name in a closed root, under closed details",
+ "#dup-named",
+ true
+ )]
+ [InlineData(
+ "a button slotted into an HTML slot under closed details in a closed root, after an SVG element named slot",
+ "#svg-first",
+ true
+ )]
+ [InlineData("a button slotted by a name holding U+0000 into a shown slot of a closed root", "#nul-named", false)]
+ [InlineData(
+ "a button in the first HTML summary of closed details, after a summary element that is not HTML",
+ "#html-summary-after-foreign",
+ false
+ )]
+ [InlineData(
+ "a button in the body of closed details whose first child is a summary element that is not HTML",
+ "#foreign-summary-body",
+ true
+ )]
+ [InlineData("a light button in closed details whose body CSS shows", "#expanded-light", false)]
+ [InlineData("a shadow button in closed details whose body CSS shows", "#expanded-shadow", false)]
+ [InlineData(
+ "a button slotted under content-visibility: hidden on display: contents in a closed root",
+ "#cv-contents-closed",
+ false
+ )]
+ [InlineData(
+ "a button slotted under content-visibility: hidden on display: contents in an open root",
+ "#cv-contents-open",
+ false
+ )]
+ [InlineData(
+ "a button slotted under content-visibility: hidden on an inline element in a closed root",
+ "#cv-inline-closed",
+ false
+ )]
+ [InlineData("a shadow button under content-visibility: hidden on display: contents", "#cv-contents-direct", false)]
+ [InlineData("a button in a table row with content-visibility: hidden", "#cv-tr", false)]
+ [InlineData("a button slotted into closed details whose body CSS shows, in an open root", "#slotted-shown", false)]
+ [InlineData(
+ "a button slotted into closed details whose body CSS shows, in a closed root",
+ "#slotted-shown-closed",
+ false
+ )]
+ [InlineData("a button under a details element that is not HTML", "#in-foreign-details", false)]
+ [InlineData(
+ "a light button in closed details whose body is laid out as display: contents",
+ "#laid-out-light",
+ false
+ )]
+ [InlineData(
+ "a shadow button in closed details whose body is laid out as display: contents",
+ "#laid-out-shadow",
+ false
+ )]
+ [InlineData("a button in a table with content-visibility: hidden", "#cv-table", false)]
+ [InlineData(
+ "a button slotted under a table with content-visibility: hidden in a closed root",
+ "#cv-table-closed",
+ false
+ )]
+ [InlineData("a button under an inline table with content-visibility: hidden", "#cv-inline-table", false)]
+ [InlineData("a button under ruby with content-visibility: hidden", "#cv-ruby", false)]
+ [InlineData("a button under an inline list item with content-visibility: hidden", "#cv-inline-li", false)]
+ [InlineData("a link in an inline svg with content-visibility: hidden", "#cv-svg-link", true)]
+ [InlineData("a button under an inline block with content-visibility: hidden", "#cv-inline-block", true)]
+ [InlineData("text in an inline button with content-visibility: hidden", "#cv-button-span", true)]
+ [InlineData("text in a ruby button with content-visibility: hidden", "#cv-ruby-button-span", true)]
+ [InlineData(
+ "a link in an svg in a foreignObject, with content-visibility: hidden on that svg",
+ "#cv-fo-svg-link",
+ true
+ )]
+ [InlineData(
+ "a button whose slot attribute is in a namespace, so it goes to the default slot of a closed root",
+ "#ns-slot",
+ false
+ )]
+ [InlineData(
+ "a button slotted by name past a slot whose name attribute is in a namespace, in a closed root",
+ "#ns-name",
+ false
+ )]
+ [InlineData(
+ "a button in a display: contents fieldset with content-visibility: hidden",
+ "#cv-fieldset-contents",
+ false
+ )]
+ public async Task Case(string description, string selector, bool hidden)
+ {
+ _ = description;
+ var page = await SetUpAsync();
+ Assert.Equal((hidden, hidden), await HiddenOfAsync(page, selector));
+ }
+
+ // Partial: Microsoft.Playwright 1.64 bundles a Chromium that reads content under content-visibility: hidden on a nested svg as hidden, so
+ // its isHidden disagrees with upstream's playwright-core 1.65.1. Only the reader's half is checked until the package moves (see the PR report).
+ [Theory]
+ [InlineData(
+ "a link in an svg nested in another, with content-visibility: hidden on the inner one",
+ "#cv-inner-svg-link",
+ false
+ )]
+ [InlineData(
+ "a link in a block svg nested in another, with content-visibility: hidden on the inner one",
+ "#cv-inner-block-svg-link",
+ false
+ )]
+ public async Task Partial_Case(string description, string selector, bool hidden)
+ {
+ _ = description;
+ var page = await SetUpAsync();
+ var read = await chromium.ReadAsync(page.Locator(selector));
+ Assert.Equal(hidden, read!.Hidden);
+ }
+
+ [Fact]
+ public async Task Lists_only_the_buttons_that_render_in_the_agent_tree()
+ {
+ var page = await SetUpAsync();
+ var nodes = await chromium.CaptureAsync(200, page);
+ var buttons = nodes.Where(node => node.Role == "button").Select(node => node.Name);
+ Assert.Equal(
+ [
+ "In summary slot",
+ "In summary",
+ "In open",
+ "Closed summary slot",
+ "Manual summary",
+ "Direct summary",
+ "Past an SVG slot",
+ "Named with a NUL",
+ "HTML summary after a foreign one",
+ "In foreign details",
+ "Expanded light",
+ "Expanded shadow",
+ "Contents closed",
+ "Contents open",
+ "Inline closed",
+ "Contents direct",
+ "Slotted shown",
+ "Slotted shown closed",
+ "Row button",
+ "Laid out light",
+ "Laid out shadow",
+ "Table button",
+ "Table slotted",
+ "Inline table button",
+ "Ruby button",
+ "Inline item button",
+ "Inline button",
+ "Ruby button",
+ "Fieldset contents",
+ "Namespaced slot attribute",
+ "Namespaced slot name",
+ ],
+ buttons
+ );
+ Assert.Contains(nodes, node =>
+ new[] { node.Name, node.Text }.Any(text => text?.Contains("Loose text under a box-less wrapper") == true)
+ );
+ }
+
+ [Fact]
+ public async Task Hides_a_button_under_a_closed_details_adopted_from_another_frame()
+ {
+ var other = await OtherPageAsync();
+ await other.SetContentAsync(
+ ""
+ );
+ await other.WaitForFunctionAsync(
+ "() => document.querySelector('iframe')?.contentDocument?.querySelector('details') != null"
+ );
+ await other.EvaluateAsync(
+ "() => document.body.append(document.querySelector('iframe').contentDocument.querySelector('details'))"
+ );
+ Assert.Equal((true, true), await HiddenOfAsync(other, "#adopted"));
+ await other.EvaluateAsync("() => document.querySelector('details').setAttribute('open', '')");
+ Assert.Equal((false, false), await HiddenOfAsync(other, "#adopted"));
+ }
+
+ [Fact]
+ public async Task Reads_the_slots_of_a_closed_root_once_per_read_however_many_children_its_host_slots()
+ {
+ var other = await OtherPageAsync();
+ var rows =
+ string.Concat(Enumerable.Range(0, 1000).Select(index => $"Row"))
+ + string.Concat(Enumerable.Repeat("Row", 1000));
+ var slots =
+ string.Concat(Enumerable.Range(0, 1000).Select(index => $""))
+ + "";
+ await other.SetContentAsync(ManyHost(rows, slots));
+ await other.EvaluateAsync(
+ """
+ () => {
+ const counts = { scans: 0, lists: 0 };
+ globalThis.counts = counts;
+ const scan = HTMLSlotElement.prototype.assignedElements;
+ HTMLSlotElement.prototype.assignedElements = function (options) {
+ counts.scans += 1;
+ return scan.call(this, options);
+ };
+ const list = ShadowRoot.prototype.querySelectorAll;
+ ShadowRoot.prototype.querySelectorAll = function (selectors) {
+ if (selectors === "slot") counts.lists += 1;
+ return list.call(this, selectors);
+ };
+ }
+ """
+ );
+ await chromium.CaptureAsync(200, other);
+ // One listing of the root's 1,001 slots, not one per slotted child, and a root that assigns by name never lists what a slot holds.
+ var counts = await other.EvaluateAsync("() => [globalThis.counts.scans, globalThis.counts.lists]");
+ Assert.Equal(new[] { 0, 1 }, counts);
+ }
+
+ [Theory]
+ [InlineData("a named slot each", 100)]
+ [InlineData("one default slot", 1000)]
+ public async Task Reads_one_match_of_a_locator_slotted_into_a_closed_root_by_name_without_listing_what_the_slots_hold(
+ string shape,
+ int count
+ )
+ {
+ var other = await OtherPageAsync();
+ var named = shape == "a named slot each";
+ var slots =
+ (named ? string.Concat(Enumerable.Range(0, count).Select(index => $"")) : "")
+ + "";
+ var rows = string.Concat(
+ Enumerable
+ .Range(0, count)
+ .Select(index => named ? $"" : "")
+ );
+ await other.SetContentAsync(ManyHost(rows, slots));
+ var work = await other.EvaluateAsync(
+ """
+ (engineSource) => {
+ const counts = { held: 0, lists: 0, shown: 0 };
+ const scan = HTMLSlotElement.prototype.assignedElements;
+ HTMLSlotElement.prototype.assignedElements = function (options) {
+ const found = scan.call(this, options);
+ counts.held += found.length;
+ return found;
+ };
+ const list = ShadowRoot.prototype.querySelectorAll;
+ ShadowRoot.prototype.querySelectorAll = function (selectors) {
+ if (selectors === "slot") counts.lists += 1;
+ return list.call(this, selectors);
+ };
+ const engine = (new Function("return (" + engineSource + ")()"))();
+ // The visible: true engine, called once per candidate the way a locator reads its matches.
+ for (const button of Array.from(document.querySelectorAll("many-host > button"))) counts.shown += engine.queryAll(button, "").length;
+ return [counts.held, counts.lists, counts.shown];
+ }
+ """,
+ ShownSelector.ShownSelectorEngineSource
+ );
+ // Every match shown, one listing of the slots per match, and nothing a slot holds read: the slot comes from the button's name.
+ Assert.Equal(new[] { 0, count, count }, work);
+ }
+
+ [Fact]
+ public async Task Looks_for_the_summary_of_a_wide_closed_details_once_per_read()
+ {
+ var other = await OtherPageAsync();
+ // No summary, so every look walks all 2,000 children.
+ await other.SetContentAsync($"{string.Concat(Enumerable.Repeat("Row", 2000))}");
+ await other.EvaluateAsync(CountDetailsReads("['children', 'firstElementChild', 'nextElementSibling']"));
+ await chromium.CaptureAsync(3000, other);
+ // One walk of the children, plus whatever else of the read steps through them; never one walk per child.
+ Assert.True(await other.EvaluateAsync("() => globalThis.counter.reads") <= 3 * 2000);
+ }
+
+ [Fact]
+ public async Task Never_looks_for_the_summary_of_an_open_details_so_reading_its_children_one_call_each_stays_linear()
+ {
+ var other = await OtherPageAsync();
+ // No summary, so a look would walk all 100 children, once per reader call.
+ await other.SetContentAsync(
+ $"{string.Concat(Enumerable.Repeat("", 100))}"
+ );
+ await other.EvaluateAsync(CountDetailsReads("['firstElementChild', 'nextElementSibling']"));
+ // A locator reads each match in its own reader call.
+ for (var index = 0; index < 100; index++)
+ {
+ await chromium.ReadAsync(other.Locator("details > button").Nth(index));
+ }
+
+ // A look per call would be 100 x 100 steps; each call's own work on its button is a few.
+ Assert.True(await other.EvaluateAsync("() => globalThis.counter.reads") <= 5 * 100);
+ }
+
+ [Fact]
+ public async Task Reads_a_table_cell_with_content_visibility_hidden_as_skipping_what_is_in_it()
+ {
+ var page = await SetUpAsync();
+ // Chromium skips a table cell's contents, as checkVisibility() reports; Firefox and WebKit paint them.
+ var read = await chromium.ReadAsync(page.Locator("#cv-td"));
+ Assert.True(read!.Hidden);
+ }
+
+ [Fact]
+ public async Task Reads_an_inline_fieldset_with_content_visibility_hidden_as_skipping_what_is_in_it()
+ {
+ var page = await SetUpAsync();
+ // A fieldset makes a box of its own whatever its display; Chromium and Firefox skip its contents, WebKit paints them.
+ Assert.Equal((true, true), await HiddenOfAsync(page, "#cv-fieldset-inline"));
+ // Its own text renders no more than its button does, so the agent's tree does not carry it.
+ Assert.Equal("", await page.Locator("#cv-fieldset").EvaluateAsync("el => el.innerText"));
+ var nodes = await chromium.CaptureAsync(200, page);
+ Assert.DoesNotContain(nodes, node =>
+ new[] { node.Name, node.Text }.Any(text => text?.Contains("Loose fieldset text") == true)
+ );
+ }
+
+ [Fact]
+ public async Task Does_not_walk_into_an_inline_fieldset_with_content_visibility_hidden_while_building_the_agent_tree()
+ {
+ var other = await OtherPageAsync();
+ await other.SetContentAsync(
+ $""
+ );
+ await other.EvaluateAsync(
+ """
+ () => {
+ const counter = { styled: 0 };
+ globalThis.counter = counter;
+ const skipped = document.getElementById("skipped");
+ const style = window.getComputedStyle;
+ window.getComputedStyle = function (el, pseudo) {
+ if (el !== skipped && skipped.contains(el)) counter.styled += 1;
+ return style.call(window, el, pseudo);
+ };
+ }
+ """
+ );
+ await chromium.CaptureAsync(500, other);
+ // Nothing under the fieldset renders, so the walk stops at it rather than reading each of its 200 buttons.
+ Assert.Equal(0, await other.EvaluateAsync("() => globalThis.counter.styled"));
+ }
+
+ private static string ManyHost(string rows, string slots) =>
+ $$"""
+ {{rows}}
+ """;
+
+ private static string CountDetailsReads(string properties) =>
+ $$"""
+ () => {
+ const counter = { reads: 0 };
+ globalThis.counter = counter;
+ for (const name of {{properties}}) {
+ const property = Object.getOwnPropertyDescriptor(Element.prototype, name) ?? Object.getOwnPropertyDescriptor(Document.prototype, name);
+ Object.defineProperty(Element.prototype, name, {
+ configurable: true,
+ get() {
+ if (this.localName === 'details' || this.parentElement?.localName === 'details') counter.reads += 1;
+ return property.get.call(this);
+ },
+ });
+ }
+ }
+ """;
+}