Skip to content

perf(renderer): mirror modal overlays to body attributes instead of body:has() - #34932

Merged
OrcaWin merged 1 commit into
mainfrom
OrcaWin/body-overlay-attributes
Oct 28, 2026
Merged

OrcaWin merged 1 commit into
mainfrom
OrcaWin/body-overlay-attributes

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 0 0 0 0
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​55 $\color{#cf222e}{\Huge{\mathbf{−}}}$​9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​46

Problem

Three rules in main.css keyed on body:has(> [data-slot='dialog-overlay'], …): the modal backdrop blur, and the toaster's z-index and pointer-events above modals. Blink anchors :has() invalidation on <body>. Because the blur rule's subject (.app-layout > :not(.window-controls)) is too generic to target, any DOM insertion anywhere in the app invalidates the whole document. A trace of context menus, tooltips and right-sidebar tab changes showed 10 full-document restyles (≥900 elements each).

Change

body-overlay-attributes.ts watches only <body>'s direct children and mirrors overlay presence to data- attributes on <body>. The three rules now key on those attributes instead of :has(). The other :has() rules left in the app are anchored on small subtrees.

Measurements

Same interaction burst (context menus, tooltip hover, right-sidebar tab change), with style-invalidation tracing on:

main this PR
Full-document restyles 10 0
Elements restyled 16,335 3,399
Total style time 113.6 ms 63.8 ms

Opening or closing a modal still restyles the document once, as it did before.

tests/e2e/modal-scene-blur.spec.ts passes 5/5. It covers dialog blur in dark and light themes, the palette, Space window dialogs and onboarding.

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0907f139-4ef3-469a-a70d-459e8337546a
Commits

Reviewing files that changed from the base of the PR and between d3af8c3 and 04a0c5c.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
Walkthrough

The change adds a utility that synchronizes body attributes with direct-child modal and onboarding overlays. Renderer entry points and the component fixture explorer install the utility, with HMR cleanup registered where described. Toast detection uses the shared modal-overlay selector. CSS uses the body attributes to control toaster stacking, toast pointer events, and app-layout blur.

Priority: Low

Merge Risk: Low · previous review d3af8

Body-level UI changes may do avoidable main-thread work. A direct-child check would address it, but the demonstrated risk is bounded and does not block merge.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description explains the problem, implementation, performance measurements, and test result, but it does not follow the required template. It omits ELI5, Linked Issue, Visual Proof or N/A, structu… Update the description to include all required template sections. Add the linked issue, visual proof or an explicit N/A with justification, testing steps and platform coverage, AI disclosure if applicable, review notes, checklist status, an…
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly describes the main change: replacing renderer modal-overlay detection through body:has() with mirrored body attributes. It is concise and specific.
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 7 files. (1 skipped: 1 unsupported.)

Full details: Description check

Explanation

The description explains the problem, implementation, performance measurements, and test result, but it does not follow the required template. It omits ELI5, Linked Issue, Visual Proof or N/A, structured Testing, Notes, Checklist, and other required sections.

Resolution

Update the description to include all required template sections. Add the linked issue, visual proof or an explicit N/A with justification, testing steps and platform coverage, AI disclosure if applicable, review notes, checklist status, and explanations for any unchecked items.

Finishing Touches: 💡 1
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b79c3f82-a5e0-41dd-be74-81cc816546da
Commits

Reviewing files that changed from the base of the PR and between 31f3c52 and d3af8c3.

Files selected for processing: 8
  • src/renderer/src/assets/main.css
  • src/renderer/src/component-fixtures/component-fixture-explorer.tsx
  • src/renderer/src/components/ui/sonner.tsx
  • src/renderer/src/lib/body-overlay-attributes.ts
  • src/renderer/src/main.tsx
  • src/renderer/src/popout.tsx
  • src/renderer/src/space.tsx
  • src/renderer/src/web/main.tsx

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

// toggleAttribute is a no-op when the state is unchanged, so unrelated portals cost no restyle.
body.toggleAttribute(
'data-modal-overlay-open',
body.querySelector(MODAL_OVERLAY_CHILD_SELECTOR) !== null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Performance & Scalability · Quick win

Supported by static analysis

Script executed:

sed -n '1,110p' src/renderer/src/lib/body-overlay-attributes.ts
sed -n '470,505p' src/renderer/src/assets/main.css
rg -n 'MODAL_OVERLAY_CHILD_SELECTOR|data-modal-overlay-open|data-onboarding-overlay-open' src/renderer tests

Repository: stablyai/orca

Length of output: 3546


Web query:

Chromium 150 SelectorQuery multiple selectors :scope > querySelector slow path descendants ElementTraversal::DescendantsOf selector_query.cc

Result:

<source_evidence>
<source kind="open_page">
<title>third_party/blink/renderer/core/css/selector_query.cc - chromium/src - Git at Google</title>
<location>https://chromium.googlesource.com/chromium/src/%2B/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/css/selector_query.cc</location>
<excerpt>citeturn1view0 [wordlim: 200] Crawled: 3 weeks ago; Content type: text/html; Source: open({&quot;ref_id&quot;:&quot;turn0search0&quot;,&quot;lineno&quot;:null}); Total lines: 567
L0: 【0†Sign in†accounts.google.com】 ◑Theme
L1: 
L2: 【1†chromium】/【2†chromium】/【3†src】/【4†0aee4434a4dba42a42abaea9bfbc0cd196a63bc1】/【5†.】/【6†third_party】/【7†blink】/【8†renderer】/【9†core】/【10†css】/selector_query.cc
L3: 
L4: blob: 3bcaae487e1f36c49e3850ca6baddbe1e2f881de [【11†file】]
L5:  | /*
L6:  | * Copyright (C) 2011, 2013 Apple Inc. All rights reserved.
L7:  | * Copyright (C) 2014 Samsung Electronics. All rights reserved.
L8:  | *
L9:  | * Redistribution and use in source and binary forms, with or without
L10:  | * modification, are permitted provided that the following conditions
L11:  | * are met:
L12:  | *
L13:  | * 1. Redistributions of source code must retain the above copyright
L14:  | * notice, this list of conditions and the following disclaimer.
L15:  | * 2. Redistributions in binary form must reproduce the above copyright
L16:  | * notice, this list of conditions and the following disclaimer in the
L17:  | * documentation and/or other materials provided with the distribution.
L18:  | *
L19:  | * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS &quot;AS IS&quot; AND ANY
L20:  | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
L21:  | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
L22:  | * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
L23:  | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
L24:  | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
L25:  | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
L26:  | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
L27:  | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
L28:  | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
L29:  | */
L30:  |
L31:  | #include &quot;third_party/blink/renderer/core/css/selector_query.h&quot;
L32:  |
L33:  | #include &lt;memory&gt;
L34:  | #include &lt;utility&gt;
L35:  |
L36:  | #include &quot;base/memory/ptr_util.h&quot;
L37:  | #include &quot;third_party/blink/renderer/bindings/core/v8/exception_state.h&quot;
L38:  | #include &quot;third_party/blink/renderer/core/css/parser/css_parser.h&quot;
L39:  | #include &quot;third_party/blink/renderer/core/css/selector_checker.h&quot;
L40:  | #include &quot;third_party/blink/renderer/core/dom/document.h&quot;
L41:  | #include &quot;third_party/blink/renderer/core/dom/element_traversal.h&quot;
L42:  | #include &quot;third_party/blink/renderer/core/dom/exception_code.h&quot;
L43:  | #include &quot;third_party/blink/renderer/core/dom/node.h&quot;
L44:  | #include &quot;third_party/blink/renderer/core/dom/nth_index_cache.h&quot;
L45:  | #include &quot;third_party/blink/renderer/core/dom/shadow_root.h&quot;
L46:  | #include &quot;third_party/blink/renderer/core/dom/static_node_list.h&quot;
L47:  | #include &quot;third_party/blink/renderer/core/html_names.h&quot;
L48:  |
L49:  | // Uncomment to run the SelectorQueryTests for stats in a release build.
L50:  | // #define RELEASE_QUERY_STATS
L51:  |
L52:  | namespace blink {
L53:  |
L54:  | using namespace HTMLNames;
L55:  |
L56:  | #if DCHECK_IS_ON() || defined(RELEASE_QUERY_STATS)
L57:  | static SelectorQuery::QueryStats&amp; CurrentQueryStats() {
L58:  | DEFINE_STATIC_LOCAL(SelectorQuery::QueryStats, stats, ());
L59:  | return stats;
L60:  | }
L61:  |
L62:  | SelectorQuery::QueryStats SelectorQuery::LastQueryStats() {
L63:  | return CurrentQueryStats();
L64:  | }
L65:  |
L66:  | #define QUERY_STATS_INCREMENT(name) \
L67:  | (void)(CurrentQueryStats().total_count++, CurrentQueryStats().name++);
L68:  | #define QUERY_STATS_RESET() (void)(CurrentQueryStats() = {});
L69:  |
L70:  | #else
L71:  |
L72:  | #define QUERY_STATS_INCREMENT(name)
L73:  | #define QUERY_STATS_RESET()
L74:  |
L75:  | #endif
L76:  |
L77:  | struct SingleElementSelectorQueryTrait {
L78:  | typedef Element* OutputType;
L79:  | static const bool kShouldOnlyMatchFirstElement = true;
L80:  | ALWAYS_INLINE static bool IsEmpty(const OutputType&amp; output) {
L81:  | return !output;
L82:  | }
L83:  | ALWAYS_INLINE static void AppendElement(OutputType&amp; output,
L84:  | Element&amp; element) {
L85:  | DCHECK(!output);
L86:  | output = &amp;element;
L87:  | }
L88:  | };
L89:  |
L90:  | struct AllElementsSelectorQueryTrait {
L91:  | typedef HeapVector&lt;Member&lt;Element&gt;&gt; OutputType;
L92:  | static const bool kShouldOnlyMatchFirstElement = false;
L93:  | ALWAYS_INLINE static bool IsEmpty(const OutputType&amp; output) {
L94:  | return output.IsEmpty();
L95:  | }
L96:  | ALWAYS_INLINE static void AppendElement(OutputType&amp; output,
L97:  | Element&amp; element) {
L98:  | output.push_back(&amp;element);
L99:  | }
L100:  | };
L101:  |
L102:  | inline bool SelectorMatches(const CSSSelector&amp; selector,
L103:  | Element&amp; element,
L104:  | const ContainerNode&amp; root_node) {
L105:  | SelectorChecker::Init init;
L106:  | init.mode = SelectorChecker::kQueryingRules;
L107:  | SelectorChecker checker(init);
L108:  | SelectorChecker::SelectorCheckingContext context(
L109:  | &amp;element, SelectorChecker::kVisitedMatchDisabled);
L110:  | context.selector = &amp;selector;
L111:  | context.scope = &amp;root_node;
L112:  | return checker.Match(context);
L113:  | }
L114:  |
L115:  | bool SelectorQuery::Matches(Element&amp; target_element) const {
L116:  | QUERY_STATS_RESET();
L117:  | if (needs_updated_distribution_)
L118:  | target_element.UpdateDistribution();
L119:  | return SelectorListMatches(target_element, target_element);
L120:  | }
L121:  |
L122:  | Element* SelectorQuery::Closest(Element&amp; target_element) const {
L123:  | QUERY_STATS_RESET();
L124:  | if (selectors_.IsEmpty())
L125:  | return nullptr;
L126:  | if (needs_updated_distribution_)
L127:  | target_element.UpdateDistribution();
L128:  |
L129:  | for (Element* current_element = &amp;target_element; current_element;
L130:  | current_element = current_element-&gt;parentElement()) {
L131:  | if (SelectorListMatches(target_element, *current_element))
L132:  | return current_element;
L133:  | }
L134:  | return nullptr;
L135:  | }
L136:  |
L137:  | StaticElementList* SelectorQuery::QueryAll(ContainerNode&amp; root_node) const {
L138:  | QUERY_STATS_RESET();
L139:  | NthIndexCache nth_index_cache(root_node.GetDocument());
L140:  | HeapVector&lt;Member&lt;Element&gt;&gt; result;
L141:  | Execute&lt;AllElementsSelectorQueryTrait&gt;(root_node, result);
L142:  | return StaticElementList::Adopt(result);
L143:  | }
L144:  |
L145:  | Element* SelectorQuery::QueryFirst(ContainerNode&amp; root_node) const {
L146:  | QUERY_STATS_RESET();
L147:  | NthIndexCache nth_index_cache(root_node.GetDocument());
L148:  | Element* matched_element = nullptr;
L149:  | Execute&lt;SingleElementSelectorQueryTrait&gt;(root_node, matched_element);
L150:  | return matched_element;
L151:  | }
L152:  |
L153:  | template &lt;typename SelectorQueryTrait&gt;
L154:  | static void CollectElementsByClassName(
L155:  | ContainerNode&amp; root_node,
L156:  | const AtomicString&amp; class_name,
L157:  | const CSSSelector* selector,
L158:  | typename SelectorQueryTrait::OutputType&amp; output) {
L159:  | for (Element&amp; element : ElementTraversal::DescendantsOf(root_node)) {
L160:  | QUERY_STATS_INCREMENT(fast_class);
L161:  | if (!element.HasClassName(class_name))
L162:  | continue;
L163:  | if (selector &amp;&amp; !SelectorMatches(*selector, element, root_node))
L164:  | continue;
L165:  | SelectorQueryTrait::AppendElement(output, element);
L166:  | if (SelectorQueryTrait::kShouldOnlyMatchFirstElement)
L167:  | return;
L168:  | }
L169:  | }
L170:  |
L171:  | inline bool MatchesTagName(const QualifiedName&amp; tag_name,
L172:  | const Element&amp; element) {
L173:  | if (tag_name == AnyQName())
L174:  | return true;
L175:  | if (element.HasLocalName(tag_name.LocalName()))
L176:  | return true;
L177:  | // Non-html elements in html documents are normalized to their camel-cased
L178:  | // version during parsing if applicable. Yet, type selectors are lower-cased
L179:  | // for selectors in html documents. Compare the upper case converted names
L180:  | // instead to allow matching SVG elements like foreignObject.
L181:  | if (!element.IsHTMLElement() &amp;&amp; element.GetDocument().IsHTMLDocument())
L182:  | return element.TagQName().LocalNameUpper() == tag_name.LocalNameUpper();
L183:  | return false;
L184:  | }
L185:  |
L186:  | template &lt;typename SelectorQueryTrait&gt;
L187:  | static void CollectElementsByTagName(
L188:  | ContainerNode&amp; root_node,
L189:  | const QualifiedName&amp; tag_name,
L190:  | typename SelectorQueryTrait::OutputType&amp; output) {
L191:  | DCHECK_EQ(tag_name.NamespaceURI(), g_star_atom);
L192:  | for (Element&amp; element : ElementTraversal::DescendantsOf(root_node)) {
L193:  | QUERY_STATS_INCREMENT(fast_tag_name);
L194:  | if (MatchesTagName(tag_name, element)) {
L195:  | SelectorQueryTrait::AppendElement(output, element);
L196:  | if (SelectorQueryTrait::kShouldOnlyMatchFirstElement)
L197:  | return;
L198:  | }
L199:  | }
L200:  | }
L201:  |
L202:  | inline bool AncestorHasClassName(ContainerNode&amp; root_node,
L203:  | const AtomicString&amp; class_name) {
L204:  | if (!root_node.IsElementNode())
L205:  | return false;
L206:  |
L207:  | for (Element* element = &amp;ToElement(root_node); element;
L208:  | element = element-&gt;parentElement()) {
L209:  | if (element-&gt;HasClassName(class_name))
L210:  | return true;
L211:  | }
L212:  | return false;
L213:  | }
L214:  |
L215:  | template &lt;typename SelectorQueryTrait&gt;
L216:  | void SelectorQuery::FindTraverseRootsAndExecute(
L217:  | ContainerNode&amp; root_node,
L218:  | typename SelectorQueryTrait::OutputType&amp; output) const {
L219:  | // We need to return the matches in document order. To use id lookup while
L220:  | // there is possiblity of multiple matches we would need to sort the
L221:  | // results. For now, just traverse the document in that case.
L222:  | DCHECK_EQ(selectors_.size(), 1u);
L223:  |
L224:  | bool is_rightmost_selector = true;
L225:  | bool is_affected_by_sibling_combinator = false;
L226:  |
L227:  | for (const CSSSelector* selector = selectors_[0]; selector;
L228:  | selector = selector-&gt;TagHistory()) {
L229:  | if (!is_affected_by_sibling_combinator &amp;&amp;
L230:  | selector-&gt;Match() == CSSSelector::kClass) {
L231:  | if (is_rightmost_selector) {
L232:  | CollectElementsByClassName&lt;SelectorQueryTrait&gt;(
L233:  | root_node, selector-&gt;Value(), selectors_[0], output);
L234:  | return;
L235:  | }
L236:  | // Since there exists some ancestor element which has the class name, we
L237:  | // need to see all children of rootNode.
L238:  | if (AncestorHasClassName(root_node, selector-&gt;Value()))
L239:  | break;
L240:  |
L241:  | const AtomicString&amp; class_name = selector-&gt;Value();
L242:  | Element* element = ElementTraversal::FirstWithin(root_node);
L243:  | while (element) {
L244:  | QUERY_STATS_INCREMENT(fast_class);
L245:  | if (element-&gt;HasClassName(class_name)) {
L246:  | ExecuteForTraverseRoot&lt;SelectorQueryTrait&gt;(*element, root_node,
L247:  | output);
L248:  | if (SelectorQueryTrait::kShouldOnlyMatchFirstElement &amp;&amp;
L249:  | !SelectorQueryTrait::IsEmpty(output))
L250:  | return;
L251:  | element =
L252:  | ElementTraversal::NextSkippingChildren(*element, &amp;root_node);
L253:  | } else {
L254:  | element = ElementTraversal::Next(*element, &amp;root_node);
L255:  | }
L256:  | }
L257:  | return;
L258:  | }
L259:  |
L260:  | if (selector-&gt;Relation() == CSSSelector::kSubSelector)
L261:  | continue;
L262:  | is_rightmost_selector = false;
L263:  | is_affected_by_sibling_combinator =
L264:  | selector-&gt;Relation() == CSSSelector::kDirectAdjacent ||
L265:  | selector-&gt;Relation() == CSSSelector::kIndirectAdjacent;
L266:  | }
L267:  |
L268:  | ExecuteForTraverseRoot&lt;SelectorQueryTrait&gt;(root_node, root_node, output);
L269:  | }
L270:  |
L271:  | template &lt;typename SelectorQueryTrait&gt;
L272:  | void SelectorQuery::ExecuteForTraverseRoot(
L273:  | ContainerNode&amp; traverse_root,
L274:  | ContainerNode&amp; root_node,
L275:  | typename SelectorQueryTrait::OutputType&amp; output) const {
L276:  | DCHECK_EQ(selectors_.size(), 1u);
L277:  |
L278:  | const CSSSelector&amp; selector = *selectors_[0];
L279:  |
L280:  | for (Element&amp; element : ElementTraversal::DescendantsOf(traverse_root)) {
L281:  | QUERY_STATS_INCREMENT(fast_scan);
L282:  | if (SelectorMatches(selector, element, root_node)) {
L283:  | SelectorQueryTrait::AppendElement(output, element);
L284:  | if (SelectorQueryTrait::kShouldOnlyMatchFirstElement)
L285:  | return;
L286:  | }
L287:  | }
L288:  | }
L289:  |
L290:  | bool SelectorQuery::SelectorListMatches(ContainerNode&amp; root_node,
L291:  | Element&amp; element) const {
L292:  | for (const auto&amp; selector : selectors_) {
L293:  | if (SelectorMatches(*selector, element, root_node))
L294:  | return true;
L295:  | }
L296:  | return false;
L297:  | }
L298:  |
L299:  | template &lt;typename SelectorQueryTrait&gt;
L300:  | void SelectorQuery::ExecuteSlow(
L301:  | ContainerNode&amp; root_node,
L302:  | typename SelectorQueryTrait::OutputType&amp; output) const {
L303:  | for (Element&amp; element : ElementTraversal::DescendantsOf(root_node)) {
L304:  | QUERY_STATS_INCREMENT(slow_scan);
L305:  | if (!SelectorListMatches(root_node, element))
L306:  | continue;
L307:  | SelectorQueryTrait::AppendElement(output, element);
L308:  | if (SelectorQueryTrait::kShouldOnlyMatchFirstElement)
L309:  | return;
L310:  | }
L311:  | }
L312:  |
L313:  | // FIXME: Move the following helper functions, AuthorShadowRootOf,
L314:  | // NextTraversingShadowTree to the best place, e.g. NodeTraversal.
L315:  | static ShadowRoot* AuthorShadowRootOf(const ContainerNode&amp; node) {
L316:  | if (!node.IsElementNode())
L317:  | return nullptr;
L318:  | ShadowRoot* root = node.GetShadowRoot();
L319:  | if (root &amp;&amp; root-&gt;IsOpenOrV0())
L320:  | return root;
L321:  | return nullptr;
L322:  | }
L323:  |
L324:  | static ContainerNode* NextTraversingShadowTree(const ContainerNode&amp; node,
L325:  | const ContainerNode* root_node) {
L326:  | if (ShadowRoot* shadow_root = AuthorShadowRootOf(node))
L327:  | return shadow_root;
L328:  |
L329:  | const ContainerNode* current = &amp;node;
L330:  | while (current) {
L331:  | if (Element* next = ElementTraversal::Next(*current, root_node))
L332:  | return next;
L333:  |
L334:  | if (!current-&gt;IsInShadowTree())
L335:  | return nullptr;
L336:  |
L337:  | ShadowRoot* shadow_root = current-&gt;ContainingShadowRoot();
L338:  | if (shadow_root == root_node)
L339:  | return nullptr;
L340:  |
L341:  | current = &amp;shadow_root-&gt;host();
L342:  | }
L343:  | return nullptr;
L344:  | }
L345:  |
L346:  | template &lt;typename SelectorQueryTrait&gt;
L347:  | void SelectorQuery::ExecuteSlowTraversingShadowTree(
L348:  | ContainerNode&amp; root_node,
L349:  | typename SelectorQueryTrait::OutputType&amp; output) const {
L350:  | for (ContainerNode* node = NextTraversingShadowTree(root_node, &amp;root_node);
L351:  | node; node = NextTraversingShadowTree(*node, &amp;root_node)) {
L352:  | if (!node-&gt;IsElementNode())
L353:  | continue;
L354:  | QUERY_STATS_INCREMENT(slow_traversing_shadow_tree_scan);
L355:  | Element* element = ToElement(node);
L356:  | if (!SelectorListMatches(root_node, *element))
L357:  | continue;
L358:  | SelectorQueryTrait::AppendElement(output, *element);
L359:  | if (SelectorQueryTrait::kShouldOnlyMatchFirstElement)
L360:  | return;
L361:  | }
L362:  | }
L363:  |
L364:  | template &lt;typename SelectorQueryTrait&gt;
L365:  | void SelectorQuery::ExecuteWithId(
L366:  | ContainerNode&amp; root_node,
L367:  | typename SelectorQueryTrait::OutputType&amp; output) const {
L368:  | DCHECK_EQ(selectors_.size(), 1u);
L369:  | DCHECK(!root_node.GetDocument().InQuirksMode());
L370:  |
L371:  | const CSSSelector&amp; first_selector = *selectors_[0];
L372:  | const TreeScope&amp; scope = root_node.ContainingTreeScope();
L373:  |
L374:  | if (scope.ContainsMultipleElementsWithId(selector_id_)) {
L375:  | // We don&#39;t currently handle cases where there&#39;s multiple elements with the
L376:  | // id and it&#39;s not in the rightmost selector.
L377:  | if (!selector_id_is_rightmost_) {
L378:  | FindTraverseRootsAndExecute&lt;SelectorQueryTrait&gt;(root_node, output);
L379:  | return;
L380:  | }
L381:  | const auto&amp; elements = scope.GetAllElementsById(selector_id_);
L382:  | for (const auto&amp; element : elements) {
L383:  | if (!element-&gt;IsDescendantOf(&amp;root_node))
L384:  | continue;
L385:  | QUERY_STATS_INCREMENT(fast_id);
L386:  | if (SelectorMatches(first_selector, *element, root_node)) {
L387:  | SelectorQueryTrait::AppendElement(output, *element);
L388:  | if (SelectorQueryTrait::kShouldOnlyMatchFirstElement)
L389:  | return;
L390:  | }
L391:  | }
L392:  | return;
L393:  | }
L394:  |
L395:  | Element* element = scope.getElementById(selector_id_);
L396:  | if (!element)
L397:  | return;
L398:  | if (selector_id_is_rightmost_) {
L399:  | if (!element-&gt;IsDescendantOf(&amp;root_node))
L400:  | return;
L401:  | QUERY_STATS_INCREMENT(fast_id);
L402:  | if (SelectorMatches(first_selector, *element, root_node))
L403:  | SelectorQueryTrait::AppendElement(output, *element);
L404:  | return;
L405:  | }
L406:  | ContainerNode* start = &amp;root_node;
L407:  | if (element-&gt;IsDescendantOf(&amp;root_node))
L408:  | start = element;
L409:  | if (selector_id_affected_by_sibling_combinator_)
L410:  | start = start-&gt;parentNode();
L411:  | if (!start)
L412:  | return;
L413:  | QUERY_STATS_INCREMENT(fast_id);
L414:  | ExecuteForTraverseRoot&lt;SelectorQueryTrait&gt;(*start, root_node, output);
L415:  | }
…[truncated]</excerpt>
</source>
<source kind="search">
<title>third_party/blink/renderer/core/css/selector_query.cc - chromium/src - Git at Google</title>
<location>https://chromium.googlesource.com/chromium/src/%2B/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/css/selector_query.cc</location>
<excerpt>citeturn0search0 [wordlim: 200] Crawled: last month;  | for (Element&amp; element : ElementTraversal::DescendantsOf(root_node)) { ...  | CollectElementsByTagName&lt;SelectorQueryTrait&gt;( ...  | SelectorQuery* SelectorQueryCache::Add(const AtomicString&amp; selectors,
 | QUERY_STATS_RESET();
 | if (selectors_.IsEmpty())
 | return nullptr;
 | if (needs_updated_distribution_)
 | target_element.UpdateDistribution();
 | 
 | for (Element* current_element = &amp;target_element; current_element;
 | current_element = current_element-&gt;parentElement()) {
 | if (SelectorListMatches(target_element, *current_element))
 | return current_element;
 | }
 | return nullptr;
 | }
 | 
 | StaticElementList* SelectorQuery::QueryAll(ContainerNode&amp; root_node) const {
 | QUERY_STATS_RESET();
 | NthIndexCache nth_index_cache(root_node.GetDocument());
 | HeapVector&lt;Member&lt;Element&gt;&gt; result;
 | Execute&lt;AllElementsSelectorQueryTrait&gt;(root_node, result);
 | return StaticElementList::Adopt(result);
 | }
 | 
 | Element* SelectorQuery::QueryFirst(ContainerNode&amp; root_node) const {
 | QUERY_STATS_RESET();
 | NthIndexCache nth_index_cache(root_node.GetDocument());
 | Element* matched_element = nullptr;
 | Execute&lt;SingleElementSelectorQueryTrait&gt;(root_node, matched_element);
 | return matched_element;
 | }
 | 
 | template &lt;typename SelectorQueryTrait&gt;
 | static void CollectElementsByClassName(
 | ContainerNode&amp; root_node,
 | const AtomicString&amp; class_name,
 | const CSSSelector* selector,
 | typename SelectorQueryTrait::OutputType&amp; output) {
 | for (Element&amp; element : ElementTraversal::DescendantsOf(root_node)) {
 | static void CollectElementsByTagName(
 | ContainerNode&amp; root_node,
 | const QualifiedName&amp; tag_name,
 | typename SelectorQueryTrait::OutputType&amp; output) {
 | DCHECK_EQ(tag_name.NamespaceURI(), g_star_atom);
 | for (Element&amp; element : ElementTraversal::DescendantsOf(root_node)) {
 | QUERY_STATS_INCREMENT(fast_tag_name);
 | if (MatchesTagName(tag_name, element)) {
 | SelectorQueryTrait::AppendElement(output, element);
 | if (SelectorQueryTrait::kShouldOnlyMatchFirstElement)
 | return;
 | }
 | }
 | }
 | 
 | inline bool AncestorHasClassName(ContainerNode&amp; root_node,
 | const AtomicString&amp; class_name) {
 | if (!root_node.IsElementNode())
 | return false;
 | 
 | for (Element* element = &amp;ToElement(root_node); element;
 | element = element-&gt;parentElement()) {
 | if (element-&gt;HasClassName(class_name))
 | return true;
 | }
 | return false;
 | }
 | 
 | template &lt;typename SelectorQueryTrait&gt;
 | void SelectorQuery::FindTraverseRootsAndExecute(
 | ContainerNode&amp; root_node,
 | typename SelectorQueryTrait::OutputType&amp; output) const {
 | // We need to return the matches in document order. To use id lookup while
 | // there is possiblity of multiple matches we would need to sort the
 | // results. For now, just traverse the document in that case.
 | DCHECK_EQ(selectors_.size(), 1u);
 | 
 | bool is_rightmost_selector = true;
 | bool is_affected_by_sibling_combinator = false;
 | 
 | for (const CSSSelector* selector = selectors_[0]; selector;
 | selector = selector-&gt;TagHistory()) {
 | if (!is_affected_by_sibling_combinator &amp;&amp;
 | selector-&gt;Match() == CSSSelector::kClass) {
 | if (is_rightmost_selector) {
 | CollectElementsByClassName&lt;SelectorQueryTrait&gt;(
 | root_node, selector-&gt;Value(), selectors_[0], output);
 | return;
 | }
 | // Since there exists some ancestor element which has the class name, we
 | // need to see all children of rootNode.
 | if (AncestorHasClassName(root_node, selector-&gt;Value()))
 | break;
 | 
 | const AtomicString&amp; class_name = selector-&gt;Value();
 | Element* element = ElementTraversal::FirstWithin(root_node);
 | while (element) {
 | QUERY_STATS_INCREMENT(fast_class);
 | if (element-&gt;HasClassName(class_name)) {
 | ExecuteForTraverseRoot&lt;SelectorQueryTrait&gt;(*element, root_node,
 | output);
 | if…[truncated]</excerpt>
</source>
<source kind="search">
<title>third_party/blink/renderer/core/css/selector_query.cc - chromium/src - Git at Google</title>
<location>https://chromium.googlesource.com/chromium/src/%2B/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/css/selector_query.cc</location>
<excerpt>citeturn2search0 [wordlim: 200] Crawled: last month;  | if (use_slow_scan_) { ...  | // so querySelector(&quot;#a&quot;) == querySelector(&quot;#A&quot;), which means we can only use
 | typedef HeapVector&lt;Member&lt;Element&gt;&gt; OutputType;
 | static const bool kShouldOnlyMatchFirstElement = false;
 | ALWAYS_INLINE static bool IsEmpty(const OutputType&amp; output) {
 | return output.IsEmpty();
 | }
 | ALWAYS_INLINE static void AppendElement(OutputType&amp; output,
 | Element&amp; element) {
 | output.push_back(&amp;element);
 | }
 | };
 | 
 | inline bool SelectorMatches(const CSSSelector&amp; selector,
 | Element&amp; element,
 | const ContainerNode&amp; root_node) {
 | SelectorChecker::Init init;
 | init.mode = SelectorChecker::kQueryingRules;
 | SelectorChecker checker(init);
 | SelectorChecker::SelectorCheckingContext context(
 | &amp;element, SelectorChecker::kVisitedMatchDisabled);
 | context.selector = &amp;selector;
 | context.scope = &amp;root_node;
 | return checker.Match(context);
 | }
 | 
 | bool SelectorQuery::Matches(Element&amp; target_element) const {
 | QUERY_STATS_RESET();
 | if (needs_updated_distribution_)
 | target_element.UpdateDistribution();
 | return SelectorListMatches(target_element, target_element);
 | }
 | 
 | Element* SelectorQuery::Closest(Element&amp; target_element) const {
 | QUERY_STATS_RESET();
 | if (selectors_.IsEmpty())
 | return nullptr;
 | if (needs_updated_distribution_)
 | target_element.UpdateDistribution();
 | 
 | for (Element* current_element = &amp;target_element; current_element;
 | current_element = current_element-&gt;parentElement()) {
 | if (SelectorListMatches(target_element, *current_element))
 | return current_element;
 | }
 | return nullptr;
 | }
 | 
 | StaticElementList* SelectorQuery::QueryAll(ContainerNode&amp; root_node) const {
 | QUERY_STATS_RESET();
 | NthIndexCache nth_index_cache(root_node.GetDocument());
 | HeapVector&lt;Member&lt;Element&gt;&gt; result;
 | Execute&lt;AllElementsSelectorQueryTrait&gt;(root_node, result);
 | return StaticElementList::Adopt(result);
 | }
 | 
 | Element* SelectorQuery::QueryFirst(ContainerNode&amp; root_node) const {
 | QUERY_STATS_RESET();
 | NthIndexCache nth_index_cache(root_node.GetDocument());
 | Element* matched_element = nullptr;
 | Execute&lt;SingleElementSelectorQueryTrait&gt;(root_node, matched_element);
 | return matched_element;
 | }
 | 
 | template &lt;typename SelectorQueryTrait&gt;
 | static void CollectElementsByClassName(
 | ContainerNode&amp; root_node,
 | const AtomicString&amp; class_name,
 | const CSSSelector* selector,
 | typename SelectorQueryTrait::OutputType&amp; output) {
 | for (Element&amp; element : ElementTraversal::DescendantsOf(root_node)) {
 | // results. For now, just traverse the document in that case.
 | DCHECK_EQ(selectors_.size(), 1u);
 | 
 | bool is_rightmost_selector = true;
 | bool is_affected_by_sibling_combinator = false;
 | 
 | for (const CSSSelector* selector = selectors_[0]; selector;
 | selector = selector-&gt;TagHistory()) {
 | if (!is_affected_by_sibling_combinator &amp;&amp;
 | selector-&gt;Match() == CSSSelector::kClass) {
 | if (is_rightmost_selector) {
 | CollectElementsByClassName&lt;SelectorQueryTrait&gt;(
 | root_node, selector-&gt;Value(), selectors_[0], output);
 | return;
 | }
 | // Since there exists some ancestor element which has the class name, we
 | // need to see all children of rootNode.
 | if (AncestorHasClassName(root_node, selector-&gt;Value()))
 | break;
 | 
 | const AtomicString&amp; class_name = selector-&gt;Value();
 | Element* element = ElementTraversal::FirstWithin(root_node);
 | while (element) {
 | QUERY_STATS_INCREMENT(fast_class);
 | if (element-&gt;HasClassName(class_name)) {
 | ExecuteForTraverseRoot&lt;SelectorQueryTrait&gt;(*element, root_node,
 | output);
 | if (SelectorQueryTrait::kShouldOnlyMatchFirstElement &amp;&amp;
 | !SelectorQueryTrait::IsEmpty(output))
 | return;
 | element =
 | ElementTraversal::NextSkippingChildren(*ele…[truncated]</excerpt>
</source>
<source kind="search">
<title>M150 Branch is here!</title>
<location>https://groups.google.com/a/chromium.org/g/chromium-dev/c/_lQnOytt6-0</location>
<excerpt>citeturn2search2 [wordlim: 200] Published: 4 months ago; Crawled: 2 months ago; # M150 Branch is here! ... Branched Chromium at revision:  | 1639810
</excerpt>
</source>
<source kind="search">
<title>Element: querySelector() method - Web APIs | MDN</title>
<location>https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector</location>
<excerpt>citeturn0search1 [wordlim: 200] Crawled: yesterday;     let allChildren = parentElement.querySelectorAll(&quot;:scope &gt; span&quot;); ...     function random(number) { ... DOM# ref-for-dom-parentnode-queryselector①

# Element: querySelector() method

Baseline

Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

  * See full compatibility
  * Learn more

The `querySelector()` method of the `Element` interface returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors.

## Syntax

js
    
    `querySelector(selectors)
    `

### Parameters

`selectors`
    

A string containing one or more selectors to match. This string must be a valid CSS selector string; if it isn&#39;t, a `SyntaxError` exception is thrown.

Note that the HTML specification does not require attribute values to be valid CSS identifiers. If a `class` or `id` attribute value is not a valid CSS identifier, then you must escape it before using it in a selector, either by calling `CSS.escape()` on the value, or using one of the techniques described in Escaping characters. See Escaping attribute values for an example.

### Return value

The first descendant element of `baseElement` which matches the specified group of `selectors`. The entire hierarchy of elements is considered when matching, including those outside the set of elements including `baseElement` and its descendants; in other words, `selectors` is first applied to the whole document, not the `baseElement`, to generate an initial list of potential elements. The resulting elements are then examined to see if they are descendants of `baseElement`. The first match of those remaining elements is returned by the `querySelector()` method.

If no matches are found, the returned value is `null`.

### Exceptions

`SyntaxError` `DOMException`
    

Thrown if the specified `selectors` are invalid.

## Examples

Let&#39;s consider a few examples.

### Find a specific element with specific values of an attribute

In this first example, the first `&lt;style&gt;` element which either has no type or has type &quot;text/css&quot; in the HTML document body is returned:
</excerpt>
</source>
<omitted_sources count="47">Additional source records were omitted from this bounded result.</omitted_sources>
</source_evidence>

Citations:

- 1: https://chromium.googlesource.com/chromium/src/%2B/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/css/selector_query.cc
- 2: https://chromium.googlesource.com/chromium/src/%2B/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/css/selector_query.cc
- 3: https://groups.google.com/a/chromium.org/g/chromium-dev/c/_lQnOytt6-0?utm_source=openai

Script executed:

set -o pipefail
printf '%s\n' '--- changed file and nearby tests ---'
rg -n -F --glob '*.{ts,tsx}' -e 'installBodyOverlayAttributes' -e 'document.body.append' -e 'document.body.remove' -e 'createPortal' -e 'portal' src/renderer tests | head -240
printf '%s\n' '--- performance measurements/tests mentioning overlays or style work ---'
rg -n -i --glob '*.{ts,tsx,md,json}' -e 'style recalcul' -e 'restyle' -e 'elements restyled' -e 'modal.*blur' -e 'overlay' tests src/renderer | head -260
printf '%s\n' '--- relevant diff against merge base ---'
git diff --unified=35 2d3e7e452000c26433650d75422e79a06be80684 d3af8c371f2277181a2aa94d73c1d486f442c7d8 -- src/renderer/src/lib/body-overlay-attributes.ts src/renderer/src/components/ui/sonner.tsx

Repository: stablyai/orca

Length of output: 41573


Script executed:

set -o pipefail
python3 - <<'PY'
import base64, urllib.request
urls = [
  "https://chromium.googlesource.com/chromium/src/+/refs/tags/150.0.7871.250/third_party/blink/renderer/core/css/selector_query.cc?format=TEXT",
  "https://chromium.googlesource.com/chromium/src/+/refs/tags/150.0.7871.250/third_party/blink/renderer/core/css/selector_query_test.cc?format=TEXT",
]
for url in urls:
    print("URL", url)
    try:
        data = urllib.request.urlopen(url, timeout=15).read()
        text = base64.b64decode(data).decode("utf-8", "replace")
        lines = text.splitlines()
        for i, line in enumerate(lines):
            if "DescendantsOf" in line or ("slow" in line.lower() and "path" in line.lower()) or ("multiple" in line.lower() and "selector" in line.lower()):
                lo, hi = max(0, i-4), min(len(lines), i+5)
                print("\n".join(f"{n+1}:{lines[n]}" for n in range(lo, hi)))
                print("---")
    except Exception as exc:
        print(type(exc).__name__, exc)
PY
printf '%s\n' '--- body-overlay references and direct body portal patterns ---'
rg -n -F --glob '*.{ts,tsx}' -e 'installBodyOverlayAttributes' -e 'document.body.append' -e 'document.body.remove' -e 'createPortal' -e 'container={document.body}' -e 'container: document.body' src/renderer tests || test "$?" -eq 1
printf '%s\n' '--- repository performance/test evidence for this helper ---'
rg -n -i --glob '*.{ts,tsx,md,json}' -e 'body-overlay-attributes' -e 'style recalcul' -e 'full-document' -e 'elements restyled' -e 'overlay.*mutation' -e 'MutationObserver' tests src/renderer || test "$?" -eq 1

Repository: stablyai/orca

Length of output: 41342


Use a bounded direct-child check for modal overlays.

body.querySelector(MODAL_OVERLAY_CHILD_SELECTOR) runs on every body child-list callback. Chromium 150 uses its slow path for multiple selectors, which scans body descendants before applying the :scope > match. The selector only matches direct body children, so use body.children instead.

🐛 Suggested fix
--- "a/src/renderer/src/lib/body-overlay-attributes.ts"
+++ "b/src/renderer/src/lib/body-overlay-attributes.ts"
@@ -15,7 +15,9 @@
     // toggleAttribute is a no-op when the state is unchanged, so unrelated portals cost no restyle.
     body.toggleAttribute(
       'data-modal-overlay-open',
-      body.querySelector(MODAL_OVERLAY_CHILD_SELECTOR) !== null
+      Array.from(body.children).some((child) =>
+        child.matches("[data-slot='dialog-overlay'], [data-slot='sheet-overlay']")
+      )
     )
     body.toggleAttribute(
       'data-onboarding-overlay-open',
Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
body.querySelector(MODAL_OVERLAY_CHILD_SELECTOR) !== null
Array.from(body.children).some((child) =>
child.matches("[data-slot='dialog-overlay'], [data-slot='sheet-overlay']")
)

…ody:has()

A body:has() rule with a descendant subject (the modal blur and toast rules) made
Chromium invalidate the whole document's style on every DOM mutation anywhere in
the app. A workspace switch paid two full-document recalcs (~1200 elements each,
~9 ms). A childList-only MutationObserver on body now mirrors the overlays into
data-modal-overlay-open / data-onboarding-overlay-open and the rules key on those.
@OrcaWin
OrcaWin force-pushed the OrcaWin/body-overlay-attributes branch from d3af8c3 to 04a0c5c Compare October 28, 2026 11:22
@OrcaWin
OrcaWin merged commit c126251 into main Oct 28, 2026
34 checks passed
nwparker added a commit that referenced this pull request Oct 29, 2026
…ole subtrees (#36098)

Fixes #34312. Takes over naufaldi#1 by @naufaldi, with the main.css part dropped because #34932 already covers it.

- SshTargetCard and the reasoning chevron now use the scoped `[[class~='group/x']:has(:focus-visible)_&]` shape. Tailwind's `group-has-*` compiles to a non-subject `:has()` whose subject is `*`, and that rule made Blink restyle whole subtrees on every mutation. This change is the entire measured win: 19.4 → 1.6 ms, 12.5 → 3.6 ms and 8.0 → 2.4 ms per mutation.
- rich-markdown-editor.css drops a redundant `:has()` on the TOC header, as defence in depth.
- Adds a guard, check-has-restyle-scope.mjs. It compiles the renderer's Tailwind CSS, adds plain stylesheets and the listed vendor stylesheets, and fails on any non-subject `:has()` whose subject has no class, id or attribute. Three pdf.js rules are baselined after being measured as harmless. It runs in lint, check:changed and PR CI in about 1.5 s.

Co-authored-by: Naufaldi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant