Skip to content

fix(web_core): scope basic catalog styles to target root in shadow DOM (#4279) - #4286

Open
jihanurrahman33 wants to merge 8 commits into
a2ui-project:mainfrom
jihanurrahman33:fix/4279-web-core-basic-catalog-shadow-styles
Open

jihanurrahman33 wants to merge 8 commits into
a2ui-project:mainfrom
jihanurrahman33:fix/4279-web-core-basic-catalog-shadow-styles

Conversation

@jihanurrahman33

Copy link
Copy Markdown
Contributor

Summary

Fixes #4279.

When mounting an A2UI renderer with the basic catalog inside a shadow root (such as in Streamlit or Web Components), BasicCatalogA2uiLitElement.connectedCallback() called injectBasicCatalogStyles() with no argument, and injectBasicCatalogStyles unconditionally adopted the default stylesheet into document.adoptedStyleSheets. This leaked :where(:root) { color-scheme: light dark; } and --a2ui-* custom properties onto the host document.

This PR:

  • Updates injectBasicCatalogStyles(targetRoot?: Document | ShadowRoot) to adopt into targetRoot ?? document, avoiding document.adoptedStyleSheets mutation when targetRoot is a ShadowRoot.
  • Updates BasicCatalogA2uiLitElement.connectedCallback() to pass this.getRootNode() when it is a ShadowRoot.
  • Expands DEFAULT_CSS selectors from :where(:root) to :where(:root, :host) (and adds :where(:host(.a2ui-dark)) and :where(:host(.a2ui-light))) so default theme variables and color-scheme apply correctly to the shadow host when adopted into a shadow root without bleeding onto the document.
  • Adds regression unit tests verifying that mounting a basic catalog element or calling injectBasicCatalogStyles inside a ShadowRoot adopts into the shadow root without polluting document.adoptedStyleSheets.

Verification

  • Ran @a2ui/web_core unit and conformance tests (corepack yarn test), 1,650 tests passing (including new regression tests).
  • Ran @a2ui/lit test suite, all unit and integration tests passing.
  • Ran @a2ui/react test suite, all unit and integration tests passing.
  • Verified lint and Prettier formatting across modified files.

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request scopes the injection of basic catalog styles to the enclosing ShadowRoot when a component connects inside a shadow tree, preventing pollution of document.adoptedStyleSheets. It updates CSS selectors to support :host rules, refactors injectBasicCatalogStyles to target the specified root, and adds corresponding tests and DOM setup mocks. Feedback on these changes suggests using 'adoptedStyleSheets' in root instead of root instanceof ShadowRoot for cross-realm safety, and providing a fallback mechanism (such as a <style> tag) for environments that do not support stylesheet adoption.

Comment on lines +57 to +60
const root = this.getRootNode();
const targetRoot =
typeof ShadowRoot !== 'undefined' && root instanceof ShadowRoot ? root : undefined;
injectBasicCatalogStyles(targetRoot);

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.

medium

Using root instanceof ShadowRoot has limitations in multi-frame/iframe environments and light DOM. Checking 'adoptedStyleSheets' in root is a robust, cross-realm safe approach to identify if stylesheet adoption is supported. Additionally, when using adoptedStyleSheets for component styles, ensure there is a fallback (such as injecting a <style> tag) for environments where it is not supported (like JSDOM).

    const root = this.getRootNode();
    if ('adoptedStyleSheets' in root) {
      const targetRoot = root as Document | ShadowRoot;
      targetRoot.adoptedStyleSheets = [...targetRoot.adoptedStyleSheets, basicCatalogStyles];
    } else {
      const style = document.createElement('style');
      style.textContent = basicCatalogStyles.cssText;
      root.appendChild(style);
    }
References
  1. When using adoptedStyleSheets for component styles, provide a fallback (e.g., injecting a <style> tag) for environments where it is not supported (like JSDOM).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks @gemini-code-assist! Updated in commit 548237a:

  1. Replaced root instanceof ShadowRoot with cross-realm safe detection root && root !== doc && ('host' in root || 'adoptedStyleSheets' in root).
  2. Added fallback style tag injection (<style data-a2ui-basic-catalog>) in injectBasicCatalogStyles for environments where adoptedStyleSheets is unsupported or throws, with deduplication checks.
  3. Added unit test coverage for the fallback injection path. All 1,651 tests in web_core pass cleanly.

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.

The updated implementation for cross-realm safe root detection and the fallback style tag injection mechanism is robust. Using ('host' in root || 'adoptedStyleSheets' in root) effectively handles ShadowRoot environments while maintaining compatibility with standard documents. The deduplication check in injectStyleTagFallback correctly prevents redundant style tag injection. This approach addresses the limitations of the previous implementation and ensures consistent styling across different environments.

@github-actions github-actions Bot added the status: needs-triage auto-managed: https://github.com/a2ui-project/a2ui/blob/main/scripts/triage.mjs label Nov 18, 2026
@gspencergoog
gspencergoog self-requested a review November 19, 2026 02:25

@gspencergoog gspencergoog left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This change scopes @a2ui/web_core basic catalog style adoption to the enclosing ShadowRoot when a BasicCatalogA2uiLitElement connects inside shadow DOM, changes injectBasicCatalogStyles(targetRoot) to target only targetRoot instead of also adopting into document, adds a <style data-a2ui-basic-catalog> fallback when adoptedStyleSheets is unavailable or throws, updates DEFAULT_CSS selectors with :host variants, and polyfills ShadowRoot.prototype.adoptedStyleSheets in the JSDOM test setup.

While the change addresses issue #4279, several defects should be resolved before merge: the new shadow-root no-pollution tests pass even against unfixed main because document.adoptedStyleSheets is never reset between tests, the dom-setup.ts polyfill reads ShadowRoot.prototype.adoptedStyleSheets directly and leaks a shared prototype array, and declaring color-scheme and --a2ui-* tokens directly on :host overrides inherited :root overrides while missing outer .a2ui-dark / .a2ui-light ancestor classes. Smaller issues affect :where(:host) browser compatibility, getDefaultStyleSheet() error handling, iframe and detached-node detection, and CHANGELOG.md ordering and PR linking.

🤖 Agent-generated

Comment on lines +167 to +196
it('adopts basic catalog styles only into shadow root when connected inside a shadow root', () => {
const host = document.createElement('div');
const shadowRoot = host.attachShadow({mode: 'open'});
document.body.appendChild(host);

const docSheetsBefore = [...(document.adoptedStyleSheets ?? [])];

const shadowElement = document.createElement('a2ui-test-basic-element');
shadowRoot.appendChild(shadowElement);

assert.ok(shadowRoot.adoptedStyleSheets.length > 0);
assert.deepStrictEqual([...(document.adoptedStyleSheets ?? [])], docSheetsBefore);

host.remove();
});

it('injectBasicCatalogStyles adopts into targetRoot when provided without polluting document', () => {
const host = document.createElement('div');
const shadowRoot = host.attachShadow({mode: 'open'});
document.body.appendChild(host);

const docSheetsBefore = [...(document.adoptedStyleSheets ?? [])];

injectBasicCatalogStyles(shadowRoot);

assert.ok(shadowRoot.adoptedStyleSheets.length > 0);
assert.deepStrictEqual([...(document.adoptedStyleSheets ?? [])], docSheetsBefore);

host.remove();
});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Both shadow-root tests run after line 156 has already added the basic catalog sheet to document.adoptedStyleSheets, so deduplication hides any document pollution. In the first test, shadowRoot.adoptedStyleSheets.length > 0 is already satisfied by TestBasicElement's own static styles. Both regression tests pass even if the fix in basic-catalog-a2ui-lit-element.ts and default.ts is reverted, leaving issue #4279 unguarded.

Suggested change
it('adopts basic catalog styles only into shadow root when connected inside a shadow root', () => {
const host = document.createElement('div');
const shadowRoot = host.attachShadow({mode: 'open'});
document.body.appendChild(host);
const docSheetsBefore = [...(document.adoptedStyleSheets ?? [])];
const shadowElement = document.createElement('a2ui-test-basic-element');
shadowRoot.appendChild(shadowElement);
assert.ok(shadowRoot.adoptedStyleSheets.length > 0);
assert.deepStrictEqual([...(document.adoptedStyleSheets ?? [])], docSheetsBefore);
host.remove();
});
it('injectBasicCatalogStyles adopts into targetRoot when provided without polluting document', () => {
const host = document.createElement('div');
const shadowRoot = host.attachShadow({mode: 'open'});
document.body.appendChild(host);
const docSheetsBefore = [...(document.adoptedStyleSheets ?? [])];
injectBasicCatalogStyles(shadowRoot);
assert.ok(shadowRoot.adoptedStyleSheets.length > 0);
assert.deepStrictEqual([...(document.adoptedStyleSheets ?? [])], docSheetsBefore);
host.remove();
});
it('adopts basic catalog styles only into shadow root when connected inside a shadow root', () => {
document.adoptedStyleSheets = [];
const host = document.createElement('div');
const shadowRoot = host.attachShadow({mode: 'open'});
document.body.appendChild(host);
const shadowElement = document.createElement('a2ui-test-basic-element');
shadowRoot.appendChild(shadowElement);
const sheetsAfterConnect = shadowRoot.adoptedStyleSheets.length;
assert.ok(sheetsAfterConnect > 0);
// Re-running injectBasicCatalogStyles should be a no-op if connectedCallback adopted it.
injectBasicCatalogStyles(shadowRoot);
assert.strictEqual(shadowRoot.adoptedStyleSheets.length, sheetsAfterConnect);
assert.strictEqual(document.adoptedStyleSheets.length, 0);
host.remove();
});
it('injectBasicCatalogStyles adopts into targetRoot when provided without polluting document', () => {
document.adoptedStyleSheets = [];
const host = document.createElement('div');
const shadowRoot = host.attachShadow({mode: 'open'});
document.body.appendChild(host);
injectBasicCatalogStyles(shadowRoot);
assert.strictEqual(shadowRoot.adoptedStyleSheets.length, 1);
assert.strictEqual(document.adoptedStyleSheets.length, 0);
host.remove();
});
Details

Evidence (Deduction): basic-catalog-a2ui-lit-element.test.ts:154-156 connects an element to document.body, adopting defaultStyleSheet into document.adoptedStyleSheets. afterEach (lines 139-146) never resets document.adoptedStyleSheets, so docSheetsBefore at lines 172 and 188 already contains defaultStyleSheet. At lines 174-177, TestBasicElement defines static styles (lines 68-76), which super.connectedCallback() adopts into shadowRoot.adoptedStyleSheets (a2ui-lit-element.ts:343-346), making shadowRoot.adoptedStyleSheets.length > 0 true without basic catalog styles.

Contrast with typescript/core/web_core/src/universal/a2ui-lit-element.test.ts:131, which resets document.adoptedStyleSheets = [] in afterEach. Calling injectBasicCatalogStyles(shadowRoot) after shadowRoot.appendChild(shadowElement) and asserting shadowRoot.adoptedStyleSheets.length does not grow proves the default catalog sheet was adopted by connectedCallback, independent of component static styles.

🤖 Agent-generated

Comment on lines +74 to +84
if (dom.window.ShadowRoot && !(dom.window.ShadowRoot.prototype as any).adoptedStyleSheets) {
Object.defineProperty(dom.window.ShadowRoot.prototype, 'adoptedStyleSheets', {
get() {
return (this._adoptedStyleSheets ??= []);
},
set(val) {
this._adoptedStyleSheets = val;
},
configurable: true,
});
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reading .adoptedStyleSheets directly on ShadowRoot.prototype invokes the getter on subsequent setupTestDom() calls, storing _adoptedStyleSheets on the prototype. New ShadowRoot instances inherit that shared array on read, and a native WebIDL getter on ShadowRoot.prototype throws TypeError: Illegal invocation. In-place mutations like shadowRoot.adoptedStyleSheets.push() leak across shadow roots and tests, and upgrading JSDOM to native adoptedStyleSheets will break test startup.

Suggested change
if (dom.window.ShadowRoot && !(dom.window.ShadowRoot.prototype as any).adoptedStyleSheets) {
Object.defineProperty(dom.window.ShadowRoot.prototype, 'adoptedStyleSheets', {
get() {
return (this._adoptedStyleSheets ??= []);
},
set(val) {
this._adoptedStyleSheets = val;
},
configurable: true,
});
}
if (dom.window.ShadowRoot && !('adoptedStyleSheets' in dom.window.ShadowRoot.prototype)) {
const shadowSheets = new WeakMap<object, CSSStyleSheet[]>();
Object.defineProperty(dom.window.ShadowRoot.prototype, 'adoptedStyleSheets', {
get() {
let sheets = shadowSheets.get(this);
if (!sheets) {
sheets = [];
shadowSheets.set(this, sheets);
}
return sheets;
},
set(val) {
shadowSheets.set(this, val);
},
configurable: true,
});
}
Details

Evidence (Deduction): dom-setup.ts:119 runs setupTestDom() at module load, installing the getter at dom-setup.ts:75-83. Test suites call setupTestDom() again in before() (basic-catalog-a2ui-lit-element.test.ts:39), reusing dom (dom-setup.ts:65-68). dom-setup.ts:74 reads (dom.window.ShadowRoot.prototype as any).adoptedStyleSheets, invoking the getter with this === ShadowRoot.prototype and assigning ShadowRoot.prototype._adoptedStyleSheets = [] (dom-setup.ts:77).

Using 'adoptedStyleSheets' in dom.window.ShadowRoot.prototype checks property existence without invoking the getter, and a WeakMap gives each ShadowRoot instance isolated storage without attaching an enumerable _adoptedStyleSheets property.

🤖 Agent-generated

Comment on lines +43 to +47
:where(:root, :host),
:where(.a2ui-dark),
:where(.a2ui-light),
:where(:host(.a2ui-dark)),
:where(:host(.a2ui-light)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Declaring color-scheme: light dark and all --a2ui-* variables directly on :host overrides inherited color-scheme and custom property values from :root or outer containers, even at zero specificity. Meanwhile, .a2ui-dark and :host(.a2ui-dark) cannot match classes set on an outer ancestor like <html>. Apps rendering Basic Catalog components inside a ShadowRoot lose documented :root theme overrides and document.documentElement light/dark class locking.

Avoid resetting color-scheme: light dark or overriding inherited --a2ui-* tokens on :host (for example, inherit tokens from :root unless unset). Otherwise, update default.ts and the guides so Shadow DOM consumers apply overrides and theme classes on the shadow host.

Details

Evidence (Deduction): default.ts:26-28, docs/site/src/content/docs/guides/client-integration.mdx:1173, and docs/site/src/content/docs/guides/a2ui-in-mcp-apps.mdx:811-815 document setting .a2ui-dark / .a2ui-light on <html> and overriding --a2ui-* tokens on :root or a container element. With basic-catalog-a2ui-lit-element.ts:57-63 and default.ts:145-154 scoping DEFAULT_CSS strictly to ShadowRoot, default.ts:31-33 sets color-scheme: light dark and default.ts:43-97 re-declares every --a2ui-* variable directly on :host, while default.ts:35-47 only matches .a2ui-dark / .a2ui-light inside the shadow tree or on :host itself.

Previously, DEFAULT_CSS was adopted on document, so :root overrides beat :where(:root) on <html> and inherited across Shadow DOM boundaries. <html class="a2ui-dark"> also updated light-dark() tokens before inheritance. Re-declaring tokens directly on :host inside the shadow root overrides inherited values from :root or outer wrappers.

🤖 Agent-generated

Comment on lines +43 to +47
:where(:root, :host),
:where(.a2ui-dark),
:where(.a2ui-light),
:where(:host(.a2ui-dark)),
:where(:host(.a2ui-light)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Wrapping :host and :host(...) inside :where() (here and at lines 31, 35, and 39) is unreliable across browser engines because featureless shadow hosts require direct :host selectors. Outer page styles already override shadow :host rules regardless of specificity. If a browser rejects or skips :where(:root, :host) inside a ShadowRoot, components receive no --a2ui-* default tokens at all.

-  :where(:root, :host) {
+  :where(:root), :host {
...
-  :where(.a2ui-dark), :where(:host(.a2ui-dark)) {
+  :where(.a2ui-dark), :host(.a2ui-dark) {
...
-  :where(.a2ui-light), :where(:host(.a2ui-light)) {
+  :where(.a2ui-light), :host(.a2ui-light) {
...
-  :where(:root, :host),
+  :where(:root),
+  :host,
   :where(.a2ui-dark),
   :where(.a2ui-light),
-  :where(:host(.a2ui-dark)),
-  :where(:host(.a2ui-light)) {
+  :host(.a2ui-dark),
+  :host(.a2ui-light) {
Details

Evidence (Speculation): default.ts:31,35,39,43-47 wraps :host, :host(.a2ui-dark), and :host(.a2ui-light) inside :where(...). CSS Scoping Level 1 treats shadow hosts as featureless elements matched only by direct :host compound selectors rather than inside :is() or :where(); the JSDOM tests (basic-catalog-a2ui-lit-element.test.ts:177,192) only assert adoptedStyleSheets.length > 0 without testing selector matching.

If switching to bare :host, prepend the sheet (targetAny.adoptedStyleSheets = [sheet, ...targetSheets]) or wrap defaults in @layer. Otherwise, connecting BasicCatalogA2uiLitElement later can overwrite a shadow host's own :host token declarations by source order. Verify selector matching in Chromium, Firefox, and Safari.

🤖 Agent-generated

Comment on lines +148 to +151
if ('adoptedStyleSheets' in target && Array.isArray(targetAny.adoptedStyleSheets)) {
const sheet = getDefaultStyleSheet();
const targetSheets = targetAny.adoptedStyleSheets as CSSStyleSheet[];
if (typeof targetSheets.includes === 'function' && !targetSheets.includes(sheet)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Calling getDefaultStyleSheet() outside the try block lets constructable-stylesheet errors escape instead of triggering injectStyleTagFallback. Moving it inside try also removes the redundant typeof targetSheets.includes === 'function' check after Array.isArray. In environments that expose adoptedStyleSheets without working new CSSStyleSheet() or replaceSync(), connectedCallback() throws uncaught instead of falling back to a <style> tag.

Move const sheet = getDefaultStyleSheet() and the targetSheets.includes(sheet) check inside the try block below so constructable-stylesheet errors fall back to injectStyleTagFallback(target).

Details

Evidence (Deduction): default.ts:148 calls getDefaultStyleSheet() before the try block at default.ts:152-157. getDefaultStyleSheet() executes new CSSStyleSheet() and .replaceSync(DEFAULT_CSS) (default.ts:115-116). If either throws when target.adoptedStyleSheets is an array (such as a partial polyfill), execution never reaches injectStyleTagFallback(target) at default.ts:164.

getDefaultStyleSheet() (default.ts:114-118) also assigns defaultStyleSheet = new CSSStyleSheet() before calling replaceSync(DEFAULT_CSS); constructing into a local variable first avoids caching an empty sheet if replaceSync ever throws.

🤖 Agent-generated

Comment on lines +57 to +63
const root = this.getRootNode();
const doc = this.ownerDocument ?? (typeof document !== 'undefined' ? document : null);
const targetRoot =
root && root !== doc && ('host' in root || 'adoptedStyleSheets' in root)
? (root as Document | ShadowRoot)
: undefined;
injectBasicCatalogStyles(targetRoot);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Checking root !== doc drops iframe light-DOM documents back to global document, and checking 'host' in root without verifying DocumentFragment (nodeType === 11) matches elements exposing a .host property. Disconnected elements should skip injection altogether. Components inside an iframe light DOM miss their own document's styles while polluting the parent document, and detached subtrees can mutate document or unrelated elements.

Suggested change
const root = this.getRootNode();
const doc = this.ownerDocument ?? (typeof document !== 'undefined' ? document : null);
const targetRoot =
root && root !== doc && ('host' in root || 'adoptedStyleSheets' in root)
? (root as Document | ShadowRoot)
: undefined;
injectBasicCatalogStyles(targetRoot);
if (!this.isConnected) return;
const root = this.getRootNode();
const doc = this.ownerDocument ?? (typeof document !== 'undefined' ? document : null);
const isShadowRoot = root.nodeType === 11 && 'host' in root;
const targetRoot = isShadowRoot ? (root as ShadowRoot) : (doc ?? undefined);
injectBasicCatalogStyles(targetRoot);
Details

Evidence (Deduction): At basic-catalog-a2ui-lit-element.ts:57-63: (1) in an iframe's light DOM, root === doc (this.ownerDocument), so root !== doc (line 60) is false and injectBasicCatalogStyles(undefined) targets global document (default.ts:145) instead of this.ownerDocument; (2) 'host' in root || 'adoptedStyleSheets' in root (line 60) matches detached <a> or <area> elements or custom elements with a .host property, causing injectStyleTagFallback (default.ts:178-179) to append a <style> child into that element; (3) detached elements in ordinary containers pass undefined, polluting global document.

This partially addresses the open gemini-code-assist thread at line 63 on cross-realm ShadowRoot detection. Sibling A2uiLitElement.adoptLightDomStyles() (typescript/core/web_core/src/universal/a2ui-lit-element.ts:334) still checks root instanceof ShadowRoot. Until both use the same check, cross-realm shadow trees will adopt basic catalog styles into the iframe shadow root while component styles adopt into the parent document.

🤖 Agent-generated

Comment thread typescript/core/web_core/CHANGELOG.md Outdated
@@ -1,5 +1,7 @@
## Unreleased

- Adopt basic catalog styles into the enclosing ShadowRoot when a component connects inside a shadow tree, and scope `injectBasicCatalogStyles` to `targetRoot` without polluting `document.adoptedStyleSheets` ([#4279](https://github.com/a2ui-project/a2ui/issues/4279)).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This non-breaking entry is placed above the **BREAKING CHANGE**: entries with an extra blank line and includes only the issue link without the pull request link. Consumers scanning the top of ## Unreleased for breaking changes can overlook them, and the entry lacks a link to the implementing pull request.

Move the entry below the **BREAKING CHANGE**: entries (removing the blank line at line 4) and append [#4286](https://github.com/a2ui-project/a2ui/pull/4286) alongside [#4279](https://github.com/a2ui-project/a2ui/issues/4279).

Details

Evidence (Read): typescript/core/web_core/CHANGELOG.md:3-5 places - Adopt basic catalog styles ... ([#4279](https://github.com/a2ui-project/a2ui/issues/4279)). and a blank line above - **BREAKING CHANGE**: ... at line 5, without a PR link. .agents/skills/update-changelog/SKILL.md:60 requires "Place all **BREAKING CHANGE**: entries at the **top** of the ## Unreleased section, with non-breaking additions and fixes below them." and lines 72-74 require ending each entry with [#<pr-number>](https://github.com/a2ui-project/a2ui/pull/<pr-number>).

🤖 Agent-generated

Comment on lines +173 to +180
const style = document.createElement('style');
style.setAttribute('data-a2ui-basic-catalog', '');
style.textContent = DEFAULT_CSS;
if ('head' in target && (target as Document).head) {
(target as Document).head.appendChild(style);
} else if (typeof targetAny.appendChild === 'function') {
targetAny.appendChild(style);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Creating the <style> element from target's own document avoids cross-document node creation, and guarding 'head' in target prevents falling through to document.appendChild(style) on head-less documents. Calling injectBasicCatalogStyles on a minimal or SVG/XML Document without a <head> throws HierarchyRequestError.

Suggested change
const style = document.createElement('style');
style.setAttribute('data-a2ui-basic-catalog', '');
style.textContent = DEFAULT_CSS;
if ('head' in target && (target as Document).head) {
(target as Document).head.appendChild(style);
} else if (typeof targetAny.appendChild === 'function') {
targetAny.appendChild(style);
}
const ownerDoc = 'createElement' in target ? target : (target.ownerDocument ?? document);
const style = ownerDoc.createElement('style');
style.setAttribute('data-a2ui-basic-catalog', '');
style.textContent = DEFAULT_CSS;
if ('head' in target) {
(target.head ?? target.documentElement)?.appendChild(style);
} else if (typeof targetAny.appendChild === 'function') {
targetAny.appendChild(style);
}
Details

Evidence (Deduction): default.ts:173 calls global document.createElement('style') instead of target's document, and when target is a Document with head === null, default.ts:176 is false so default.ts:179 executes target.appendChild(style), which throws HierarchyRequestError if target.documentElement already exists.

🤖 Agent-generated

Comment on lines +199 to +210
const mockRoot = document.createElement('div') as any;
// mockRoot has no adoptedStyleSheets property
injectBasicCatalogStyles(mockRoot);

const styleEl = mockRoot.querySelector('style[data-a2ui-basic-catalog]');
assert.ok(styleEl !== null);
assert.ok(styleEl.textContent?.includes('--a2ui-color-primary'));

// Re-injecting does not duplicate the style tag
injectBasicCatalogStyles(mockRoot);
const styleEls = mockRoot.querySelectorAll('style[data-a2ui-basic-catalog]');
assert.strictEqual(styleEls.length, 1);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Using a plain div tests only the non-head appendChild fallback path and does not verify fallback behavior when ShadowRoot.adoptedStyleSheets assignment throws or when targeting a Document.

Add a case using a real ShadowRoot whose adoptedStyleSheets setter throws, plus a case verifying <style data-a2ui-basic-catalog> insertion into document.head when document.adoptedStyleSheets is unavailable.

Details

Evidence (Read): basic-catalog-a2ui-lit-element.test.ts:199-201 passes document.createElement('div') as any to injectBasicCatalogStyles(mockRoot), exercising only default.ts:178-179 (appendChild) and leaving both the adoptedStyleSheets catch fallback (default.ts:155-157) and Document head.appendChild branch (default.ts:176-177) untested.

🤖 Agent-generated

@jihanurrahman33
jihanurrahman33 force-pushed the fix/4279-web-core-basic-catalog-shadow-styles branch from 548237a to d573e47 Compare November 19, 2026 05:22
@jihanurrahman33

Copy link
Copy Markdown
Contributor Author

@gspencergoog Thanks for the thorough review. Rebased onto main and addressed each point in d573e47:

  • Selectors: :host and :host(...) are now direct selectors, not wrapped in :where(). The sheet is prepended in shadow roots so a host's own :host rules still win by source order.
  • Fallbacks: getDefaultStyleSheet() and the adoption run inside the try, so a failing new CSSStyleSheet(), replaceSync() or a throwing adoptedStyleSheets setter falls back to a <style data-a2ui-basic-catalog> tag. The tag is created from the target's owner document and goes in head (or documentElement) for a Document.
  • Root detection: connectedCallback skips disconnected elements, treats a root as a shadow root only when nodeType === 11 and it has a host, and otherwise targets this.ownerDocument, so iframe light DOM no longer touches the parent document.
  • Tests: the shadow-root tests reset document.adoptedStyleSheets and assert nothing leaks into the document. I confirmed the shadow-root test fails when the fix is reverted. Added cases for a throwing shadow-root setter and for the Document head fallback.
  • dom-setup.ts: uses 'adoptedStyleSheets' in ShadowRoot.prototype and a WeakMap per shadow root.
  • CHANGELOG: entry sits under ## Unreleased with the PR link (0.16.0 shipped, so there are no breaking entries above it now).

One design call I'd like your view on: defaults stay on :host, so :root overrides and classes on <html> don't reach a shadow tree. I documented in client-integration.mdx that Shadow DOM consumers set --a2ui-* overrides and .a2ui-dark/.a2ui-light on the shadow host. Happy to switch if you prefer a different approach. A2uiLitElement.adoptLightDomStyles() still uses instanceof ShadowRoot; I left it out to keep this PR scoped.

@Varun-S10

Copy link
Copy Markdown
Collaborator

Hi @jihanurrahman33, thank you for raising the pr and updating it based on the review comments. We have verified the latest changes and they resolve the issue. I will escalate this to the team for review. Thank you for your patience and understanding.
Hi @gspencergoog, Could you please take a look?

@Varun-S10 Varun-S10 added status: needs review and removed status: needs-triage auto-managed: https://github.com/a2ui-project/a2ui/blob/main/scripts/triage.mjs labels Nov 19, 2026
github-actions Bot added a commit that referenced this pull request Nov 20, 2026
@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

📖 Docs Site Preview Deployed

Preview URL: https://a2ui.org/pr-preview/pr-4286/

Modified pages in this PR:

Built from commit a2f6cc1 · Workflow run · GitHub Pages may take ~30–60s to propagate updates. This preview is removed automatically when the PR closes.

@jihanurrahman33

jihanurrahman33 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

The kanban-e2e contrast failure came from this change. The Kanban sample sets its --a2ui-* overrides on :root, but the basic catalog defaults now sit on :host inside the shadow root and win over inherited :root values, so the "Add task" button went back to the default primary colour (ratio 4.29). Pushed b5ddce1, which moves the sample's overrides onto the a2ui-kanban-chat shadow host, as documented in client-integration.mdx. I checked both contrast tests locally, in installed Chrome rather than the Chromium CI uses: they fail without the change and pass with it. @gspencergoog this is the :root-override trade-off from the earlier review, so I would still like your view on whether defaults should stay on :host.

@jihanurrahman33
jihanurrahman33 force-pushed the fix/4279-web-core-basic-catalog-shadow-styles branch from 0161d5c to b5ddce1 Compare November 20, 2026 09:14
@jihanurrahman33

Copy link
Copy Markdown
Contributor Author

The Actions workflows for the latest push are waiting for approval (action_required), so only check-changes and cla/google have run, and both pass. Could a maintainer approve and run the workflows? Thank you.

@jihanurrahman33

Copy link
Copy Markdown
Contributor Author

@gspencergoog friendly nudge when you have a moment. Your CHANGES_REQUESTED review was against 548237a. Since then d573e47 addressed each point (test reset and leak check, dom-setup.ts polyfill, direct :host selectors, getDefaultStyleSheet() inside the try, iframe and detached-node handling, the extra fallback tests, CHANGELOG placement), and b5ddce1 fixed the kanban-e2e contrast failure that the :host change exposed.

Two things are still open on the maintainer side: the full workflow run for b5ddce1 is waiting for approval (only check-changes and cla/google have run), and I'd still like your view on keeping the defaults on :host versus supporting :root overrides. Could you re-review, or approve the workflows so CI can run? Thank you!

@jihanurrahman33
jihanurrahman33 force-pushed the fix/4279-web-core-basic-catalog-shadow-styles branch from b5ddce1 to 34cca0c Compare November 21, 2026 06:35
@jihanurrahman33

Copy link
Copy Markdown
Contributor Author

@gspencergoog This is rebased onto the latest main (the only conflict was the web_core CHANGELOG, and I kept both entries). It includes the earlier follow-ups: the review fixes in d573e47 and the Kanban sample's --a2ui-* overrides now set on the shadow host. @a2ui/web_core tests pass (1663/1663). Could you take another look at your earlier change request, and approve the Actions workflows so the full CI, including kanban-e2e, can run on the new commit?

github-actions Bot added a commit that referenced this pull request Nov 24, 2026

@gspencergoog gspencergoog left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This PR scopes @a2ui/web_core Basic Catalog default stylesheet injection to the enclosing ShadowRoot when a BasicCatalogA2uiLitElement connects inside a shadow tree, updates injectBasicCatalogStyles(targetRoot?) to adopt only into targetRoot instead of document, adds a <style data-a2ui-basic-catalog> fallback when adoptedStyleSheets is unavailable or throws, updates DEFAULT_CSS with :host selectors, polyfills ShadowRoot.prototype.adoptedStyleSheets in JSDOM, adds five tests, and updates CHANGELOG.md and client-integration.mdx.

The core scoping architecture addresses the prior review feedback well, but several issues remain before merge: :host(.a2ui-dark) and :host(.a2ui-light) raise token specificity to (0, 2, 0) and override component :host rules, CHANGELOG.md lacks the required **BREAKING CHANGE**: prefix and migration note, the <style> fallback appends instead of prepending in shadow roots, the singleton CSSStyleSheet cache fails in cross-realm iframes, the shadow-root tests omit prepend-order assertions, and client-integration.mdx contradicts Step 2's top-level injectBasicCatalogStyles() call.

🤖 Agent-generated

:host,
:where(.a2ui-dark),
:where(.a2ui-light),
:host(.a2ui-dark),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

:host(.a2ui-dark) and :host(.a2ui-light) raise the token block's specificity to (0, 2, 0), defeating the prepend ordering on line 159. Because :host on line 47 already targets the same host element where lines 38 and 42 set color-scheme, lines 50 and 51 are redundant. Toggling .a2ui-dark or .a2ui-light on a shadow host resets all --a2ui-* tokens defined in the host component's own :host stylesheet back to defaults.

   :where(:root),
   :host,
   :where(.a2ui-dark),
-  :where(.a2ui-light),
-  :host(.a2ui-dark),
-  :host(.a2ui-light) {
+  :where(.a2ui-light) {
Details

Evidence (Read): typescript/core/web_core/src/universal/basic_catalog/styles/default.ts:46-52 ":where(:root),\n :host,\n :where(.a2ui-dark),\n :where(.a2ui-light),\n :host(.a2ui-dark),\n :host(.a2ui-light) {\n --a2ui-color-background: light-dark(#eee, #111);" and default.ts:157-159 "// In a shadow root the sheet goes first, so \:host` rules from components that connect later still win by source order." Deduction: :host(.a2ui-dark)has specificity(0, 2, 0), which beats a shadow component's own :hostrule at(0, 1, 0)regardless of sheet order, and:host` on line 47 already matches the same host element.

In Light DOM, :where(:root) and :where(.a2ui-dark) both have specificity (0, 0, 0), so :root author overrides always survive .a2ui-dark. In Shadow DOM, :host(.a2ui-dark) on lines 38 and 42 already sets color-scheme on the host, while :host on line 47 sets every --a2ui-* default on that exact element at (0, 1, 0). Inner .a2ui-dark descendants inside the shadow tree continue to match :where(.a2ui-dark) on lines 38 and 48.

🤖 Agent-generated

Comment thread typescript/core/web_core/CHANGELOG.md Outdated
## Unreleased

- Add `MessageProcessor.addCatalog(catalog)`, which adds a catalog to a processor after it is built. `createSurface` messages, renderer function calls and `getRendererCapabilities` see the catalog from then on; surfaces created before the call keep the catalogs they were created with. A catalog whose id the processor already holds is rejected with `A2uiCatalogError`. The processor keeps its own copy of the array passed to its constructor, which `addCatalog` adds to, and `MessageProcessor.catalogs` lists the added catalog too ([#3303](https://github.com/a2ui-project/a2ui/issues/3303), [#3304](https://github.com/a2ui-project/a2ui/pull/3304)).
- Adopt basic catalog styles into the enclosing ShadowRoot when a component connects inside a shadow tree, and scope `injectBasicCatalogStyles` to `targetRoot` without polluting `document.adoptedStyleSheets` ([#4279](https://github.com/a2ui-project/a2ui/issues/4279), [#4286](https://github.com/a2ui-project/a2ui/pull/4286)).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This PR breaks two existing consumer contracts without a **BREAKING CHANGE**: prefix or migration steps. Shadow-mounted surfaces no longer inherit :root --a2ui-* overrides or <html> dark/light classes, and injectBasicCatalogStyles(targetRoot) no longer adopts into document. Consumers upgrading @a2ui/web_core can silently lose custom themes in shadow-DOM apps or lose document styling when passing targetRoot.

Suggested change
- Adopt basic catalog styles into the enclosing ShadowRoot when a component connects inside a shadow tree, and scope `injectBasicCatalogStyles` to `targetRoot` without polluting `document.adoptedStyleSheets` ([#4279](https://github.com/a2ui-project/a2ui/issues/4279), [#4286](https://github.com/a2ui-project/a2ui/pull/4286)).
- **BREAKING CHANGE**: Adopt basic catalog styles into the enclosing `ShadowRoot` when a component connects inside a shadow tree, and scope `injectBasicCatalogStyles(targetRoot)` exclusively to `targetRoot` instead of also adopting into `document`. Recommended migration: move `--a2ui-*` overrides and `.a2ui-dark` / `.a2ui-light` classes from `:root` / `<html>` onto the shadow host element for shadow-mounted surfaces, and call `injectBasicCatalogStyles()` without arguments if light-DOM surfaces also need `document` styles ([#4279](https://github.com/a2ui-project/a2ui/issues/4279), [#4286](https://github.com/a2ui-project/a2ui/pull/4286)).
Details

Evidence (Read): typescript/core/web_core/CHANGELOG.md:4 "- Adopt basic catalog styles into the enclosing ShadowRoot when a component connects inside a shadow tree, and scope \injectBasicCatalogStyles` to `targetRoot` without polluting `document.adoptedStyleSheets` (#4279, #4286).", docs/site/src/content/docs/guides/client-integration.mdx:1187 "The shadow root's defaults replace values set on `:root` and classes set on ``.", and .agents/skills/update-changelog/SKILL.md:63 "Annotate entries with `BREAKING CHANGE:` whenever there is: ... changes to CSS custom properties or styling inheritance contracts that consumers depend on"`.

🤖 Agent-generated

style.textContent = DEFAULT_CSS;

const parent = isDocument(target) ? (target.head ?? target.documentElement) : target;
parent?.appendChild(style);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The adoptedStyleSheets path prepends DEFAULT_CSS in shadow roots so component :host rules win by source order, but injectStyleTagFallback appends <style data-a2ui-basic-catalog> at the end of target.

Suggested change
parent?.appendChild(style);
if (isDocument(target)) {
parent?.appendChild(style);
} else {
parent?.insertBefore(style, parent.firstChild);
}
Details

Evidence (Read): typescript/core/web_core/src/universal/basic_catalog/styles/default.ts:157-159 "// In a shadow root the sheet goes first, so \:host` rules from components that connect later still win by source order.\n target.adoptedStyleSheets = isDocument(target) ? [...sheets, sheet] : [sheet, ...sheets];"vsdefault.ts:182-183 "const parent = isDocument(target) ? (target.head ?? target.documentElement) : target;\n parent?.appendChild(style);"`

🤖 Agent-generated

if (!defaultStyleSheet) {
defaultStyleSheet = new CSSStyleSheet();
defaultStyleSheet.replaceSync(DEFAULT_CSS);
const sheet = new CSSStyleSheet();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

connectedCallback explicitly handles iframe roots, but getDefaultStyleSheet() caches a single outer-realm CSSStyleSheet. Adopting that sheet into an iframe Document or ShadowRoot throws NotAllowedError and forces the fallback path on every connection. Every Basic Catalog component mounted in an iframe throws a caught DOMException, loses constructable-stylesheet adoption, and re-runs querySelector on each connect.

-let defaultStyleSheet: CSSStyleSheet | undefined;
+const defaultStyleSheets = new WeakMap<Document, CSSStyleSheet>();

-function getDefaultStyleSheet(): CSSStyleSheet {
-  if (!defaultStyleSheet) {
-    const sheet = new CSSStyleSheet();
-    sheet.replaceSync(DEFAULT_CSS);
-    defaultStyleSheet = sheet;
-  }
-  return defaultStyleSheet;
+function getDefaultStyleSheet(ownerDoc: Document): CSSStyleSheet {
+  let sheet = defaultStyleSheets.get(ownerDoc);
+  if (!sheet) {
+    const StyleSheetCtor = ownerDoc.defaultView?.CSSStyleSheet ?? CSSStyleSheet;
+    sheet = new StyleSheetCtor();
+    sheet.replaceSync(DEFAULT_CSS);
+    defaultStyleSheets.set(ownerDoc, sheet);
+  }
+  return sheet;
 }
Details

Evidence (Read): typescript/core/web_core/src/universal/basic_catalog/components/basic-catalog-a2ui-lit-element.ts:62-65 "// Checked structurally so a shadow root from another realm (such as an\n // iframe) is recognized, which \instanceof ShadowRoot` would miss."andtypescript/core/web_core/src/universal/basic_catalog/styles/default.ts:119-121 "const sheet = new CSSStyleSheet();\n sheet.replaceSync(DEFAULT_CSS);\n defaultStyleSheet = sheet;"plusdefault.ts:153-159 "const sheet = getDefaultStyleSheet(); ... if (sheets.includes(sheet)) return; ... target.adoptedStyleSheets = ...". Deduction: CSSOM rejects adopting a CSSStyleSheetwhose constructor document differs from the target document withNotAllowedError, so sheets.includes(sheet)` stays false on every element connection in an iframe.

Compute const ownerDoc = isDocument(target) ? target : (target.ownerDocument ?? document); once in injectBasicCatalogStyles and pass ownerDoc to getDefaultStyleSheet(ownerDoc). Using a WeakMap<Document, CSSStyleSheet> also allows iframe stylesheets to be garbage-collected when an iframe is removed.

🤖 Agent-generated

}
```

When the surface renders inside a shadow root, Basic Catalog components adopt the default stylesheet into that shadow root instead of `document`, so the host page's styles stay untouched. The shadow root's defaults replace values set on `:root` and classes set on `<html>`. Set the `--a2ui-*` overrides and the `.a2ui-dark` or `.a2ui-light` class on the shadow host element instead.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Line 1187 states that the host page's styles stay untouched inside a shadow root, yet Step 2 (lines 148, 177, 203) calls injectBasicCatalogStyles() with no arguments. The guide's own Lit app renders inside AgentSurfacesElement's shadow root while calling injectBasicCatalogStyles() at module load. Readers following the Lit guide or using a shadow root still adopt DEFAULT_CSS onto document unless told to skip or scope that call.

Suggested change
When the surface renders inside a shadow root, Basic Catalog components adopt the default stylesheet into that shadow root instead of `document`, so the host page's styles stay untouched. The shadow root's defaults replace values set on `:root` and classes set on `<html>`. Set the `--a2ui-*` overrides and the `.a2ui-dark` or `.a2ui-light` class on the shadow host element instead.
When the surface renders inside a shadow root, omit the top-level `injectBasicCatalogStyles()` call from [Step 2](#step-2-initialize-messageprocessor) (or pass your shadow root to `injectBasicCatalogStyles(shadowRoot)`). Basic Catalog components adopt the default stylesheet into that enclosing shadow root instead of `document`, so the host page's styles stay untouched. The shadow root's defaults replace values set on `:root` and classes set on `<html>`. Set the `--a2ui-*` overrides and the `.a2ui-dark` or `.a2ui-light` class on the shadow host element instead.
Details

Evidence (Read): docs/site/src/content/docs/guides/client-integration.mdx:177 "injectBasicCatalogStyles();", client-integration.mdx:419 "export class AgentSurfacesElement extends LitElement {", client-integration.mdx:1173 "Calling \injectBasicCatalogStyles()` in Step 2 adopts the default stylesheet into `document.adoptedStyleSheets`", vs client-integration.mdx:1187 "When the surface renders inside a shadow root, Basic Catalog components adopt the default stylesheet into that shadow root instead of `document`, so the host page's styles stay untouched."`

🤖 Agent-generated

const shadowRoot = host.attachShadow({mode: 'open'});
document.body.appendChild(host);

injectBasicCatalogStyles(shadowRoot);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

None of the five new tests check stylesheet order inside a shadow root. Mutating [sheet, ...sheets] to [...sheets, sheet] on default.ts:159 leaves every test passing, and the fallback tests run only on empty roots. A regression that appends DEFAULT_CSS after component :host styles in a shadow root will pass CI undetected.

+    const existingSheet = new CSSStyleSheet();
+    shadowRoot.adoptedStyleSheets = [existingSheet];
+
     injectBasicCatalogStyles(shadowRoot);

-    assert.strictEqual(shadowRoot.adoptedStyleSheets.length, 1);
+    assert.strictEqual(shadowRoot.adoptedStyleSheets.length, 2);
+    assert.strictEqual(shadowRoot.adoptedStyleSheets[1], existingSheet);
     assert.strictEqual(document.adoptedStyleSheets.length, 0);
Details

Evidence (Read): typescript/core/web_core/src/universal/basic_catalog/styles/default.ts:159 "target.adoptedStyleSheets = isDocument(target) ? [...sheets, sheet] : [sheet, ...sheets];" vs typescript/core/web_core/src/universal/basic_catalog/components/basic-catalog-a2ui-lit-element.test.ts:176-196 (assert.ok(sheetsAfterConnect > 0) and assert.strictEqual(shadowRoot.adoptedStyleSheets.length, 1) on an empty shadow root).

Adding a pre-existing <style> element to the shadow-root fallback test (lines 201-215) and asserting shadowRoot.firstElementChild?.matches('style[data-a2ui-basic-catalog]') will also guard the prepend behavior from M1.

🤖 Agent-generated

} catch {
// Fallback
}
const target = targetRoot ?? document;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The SSR guard checks global document before reading targetRoot. Callers passing an explicit Document or ShadowRoot in an environment without global document receive a silent no-op. Isolated JSDOM or custom-realm callers that pass targetRoot explicitly without setting globalThis.document get no styles injected.

-  if (typeof document === 'undefined') return;
-  const target = targetRoot ?? document;
+  const target = targetRoot ?? (typeof document !== 'undefined' ? document : undefined);
+  if (!target) return;
Details

Evidence (Read): typescript/core/web_core/src/universal/basic_catalog/styles/default.ts:148-150 "export function injectBasicCatalogStyles(targetRoot?: Document | ShadowRoot): void {\n if (typeof document === 'undefined') return;\n const target = targetRoot ?? document;"

🤖 Agent-generated

if (sheets.includes(sheet)) return;
// In a shadow root the sheet goes first, so `:host` rules from components
// that connect later still win by source order.
target.adoptedStyleSheets = isDocument(target) ? [...sheets, sheet] : [sheet, ...sheets];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Should DEFAULT_CSS account for adoptedStyleSheets overriding <style> :host rules in shadow roots? Shadow hosts defining --a2ui-* tokens in internal <style>:host blocks would have those tokens silently overwritten.

Details

Evidence (Deduction): default.ts:34-51 declares :host rules at (0, 1, 0) and default.ts:159 inserts them into shadowRoot.adoptedStyleSheets. Per CSSOM, adoptedStyleSheets evaluate after <style> elements in the same ShadowRoot, so any shadow host that styles :host via an internal <style> tag (such as Declarative Shadow DOM or non-constructable frameworks) loses to DEFAULT_CSS.

To settle: Verify whether @a2ui/angular ViewEncapsulation.ShadowDom or Declarative Shadow DOM hosts are in scope; if so, test a <style>:host { --a2ui-color-primary: #0f766e; }</style> shadow root in Chromium or note in client-integration.mdx:1187 that overrides must be placed in outer styles or adoptedStyleSheets.

🤖 Agent-generated

github-actions Bot added a commit that referenced this pull request Nov 24, 2026
@jihanurrahman33

Copy link
Copy Markdown
Contributor Author

@gspencergoog thanks for the second round. Pushed a2f6cc1 on top of your merge of main:

  • Removed :host(.a2ui-dark) and :host(.a2ui-light) from the token block. :host already matches the same element, so the (0, 2, 0) specificity is gone. The color-scheme rules for those classes stay.
  • The <style> fallback now goes first in a shadow root, like the adopted sheet. The test checks for it.
  • The default stylesheet is cached per document and built with that document's CSSStyleSheet, so iframes can adopt it.
  • An explicit targetRoot now works when there is no global document.
  • The shadow-root test now checks the sheet order against an existing sheet.
  • The CHANGELOG entry is marked **BREAKING CHANGE** with a migration note. It was under 0.16.1 after the merge, so I moved it to Unreleased.
  • client-integration.mdx now says to omit the top-level injectBasicCatalogStyles() call, or pass the shadow root to it.

I haven't tested your question about <style>:host blocks losing to adopted sheets. JSDOM can't settle it, so it needs a real browser. If that case is in scope, the options are a note in the docs or a different approach, and I'll follow whichever you prefer.

@a2ui/web_core tests pass (1663/1663), and lint and Prettier are clean. Could you re-review and approve the Actions workflow?

github-actions Bot added a commit that referenced this pull request Nov 24, 2026

@gspencergoog gspencergoog left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This PR scopes @a2ui/web_core Basic Catalog default stylesheet injection to the enclosing ShadowRoot when BasicCatalogA2uiLitElement connects inside shadow DOM, changes injectBasicCatalogStyles(targetRoot?) to target only targetRoot instead of also adopting into document, caches constructable stylesheets per Document in a WeakMap for cross-realm iframe support, adds :host / :host(.a2ui-dark) / :host(.a2ui-light) selectors to DEFAULT_CSS, and falls back to <style data-a2ui-basic-catalog> injection. It also updates samples/community/mcp/a2ui-kanban/client/index.html, docs/site/src/content/docs/guides/client-integration.mdx, typescript/core/web_core/CHANGELOG.md, dom-setup.ts, and basic-catalog-a2ui-lit-element.test.ts.

The author addressed 16 of 18 prior review items from Rounds 1 and 2, and all 38 active CI checks pass. Three medium findings and one low finding remain: :host { color-scheme: light dark; } breaks theme toggling in the un-updated samples/client/lit/shell/ sample, client-integration.mdx:1187 still contradicts Step 2's top-level injectBasicCatalogStyles() call in the Lit snippet, cross-document caching and disconnected-element paths lack unit tests, and getDefaultStyleSheet runs before checking Array.isArray(target.adoptedStyleSheets). An open question from Round 2 on shadow-root <style>:host precedence also awaits a maintainer decision.

🤖 Agent-generated

*/
const DEFAULT_CSS = `
:where(:root) {
:where(:root), :host {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Applying :host { color-scheme: light dark; } directly on <a2ui-shell> overrides the color-scheme inherited from document.body. Unlike samples/community/mcp/a2ui-kanban/client/index.html, the Lit shell sample was not updated for this breaking change. Once a surface renders in samples/client/lit/shell/, getComputedStyle(evt.target).colorScheme stays 'light dark' and the shell's theme toggle stops switching light and dark modes.

Details

Evidence (Deduction): typescript/core/web_core/src/universal/basic_catalog/styles/default.ts:34-36 sets :host { color-scheme: light dark; }, adopted into enclosing shadow roots by typescript/core/web_core/src/universal/basic_catalog/components/basic-catalog-a2ui-lit-element.ts:61-65. samples/client/lit/shell/app.ts:42,807,829 renders <a2ui-surface> inside <a2ui-shell>'s shadow root, while samples/client/lit/shell/index.html:107-117 sets color-scheme: var(--color-scheme) only on html, body and samples/client/lit/shell/app.ts:628-638 toggles .light/.dark on document.body after checking getComputedStyle(evt.target).colorScheme === 'dark'.

Mirror the samples/community/mcp/a2ui-kanban/client/index.html:44 update by adding a2ui-shell { color-scheme: var(--color-scheme); } in samples/client/lit/shell/index.html (outer-tree rules on the host beat inner :host), and update samples/client/lit/shell/THEMING.md:16-17 to note shadow-host overrides.

🤖 Agent-generated

}
```

When the surface renders inside a shadow root, omit the top-level `injectBasicCatalogStyles()` call from [Step 2](#step-2-initialize-messageprocessor), or pass your shadow root to `injectBasicCatalogStyles(shadowRoot)`. Basic Catalog components adopt the default stylesheet into that enclosing shadow root instead of `document`, so the host page's styles stay untouched. The shadow root's defaults replace values set on `:root` and classes set on `<html>`. Set the `--a2ui-*` overrides and the `.a2ui-dark` or `.a2ui-light` class on the shadow host element instead.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The Lit tab in Step 2 calls injectBasicCatalogStyles() at module top level, even though Step 3's AgentSurfacesElement renders into a shadow root by default. Line 1187 was updated to advise omitting that call, while Step 2's Lit tab still keeps it. Developers following the Lit guide verbatim will still pollute document.adoptedStyleSheets and see :root theme overrides ignored inside <agent-surfaces>.

Remove the injectBasicCatalogStyles import and call from the Step 2 Lit tab (lines 173 and 177), or note here that Step 3's AgentSurfacesElement uses a shadow root.

Details

Evidence (Read): docs/site/src/content/docs/guides/client-integration.mdx:1187 "When the surface renders inside a shadow root, omit the top-level \injectBasicCatalogStyles()` call from Step 2, or pass your shadow root to `injectBasicCatalogStyles(shadowRoot)`."contradictsdocs/site/src/content/docs/guides/client-integration.mdx:177 "injectBasicCatalogStyles();"paired withdocs/site/src/content/docs/guides/client-integration.mdx:419 "export class AgentSurfacesElement extends LitElement {"(which renders` inside its shadow root at line 465).

🤖 Agent-generated

}
});

it('adopts basic catalog styles only into shadow root when connected inside a shadow root', () => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The new tests cover only connected elements in the single global document and calls passing an explicit targetRoot. Cross-document sheet caching, structural shadow-root detection, isConnected === false, and no-arg injectBasicCatalogStyles() remain untested. Regressions in iframe stylesheet creation, disconnected-connect guards, or default document adoption would pass the test suite undetected.

Details

Evidence (Read): typescript/core/web_core/src/universal/basic_catalog/styles/default.ts:107,118-127 (WeakMap<Document, CSSStyleSheet> and ownerDoc.defaultView?.CSSStyleSheet ?? CSSStyleSheet) and typescript/core/web_core/src/universal/basic_catalog/components/basic-catalog-a2ui-lit-element.ts:60-65 (if (!this.isConnected) return; and structural root.nodeType === DOCUMENT_FRAGMENT_NODE && 'host' in root) have no corresponding cases in typescript/core/web_core/src/universal/basic_catalog/components/basic-catalog-a2ui-lit-element.test.ts:167-261.

Add cases for a second Document (distinct cached sheets and structural shadow-root detection) and for connectedCallback() while isConnected is false. Also test no-arg injectBasicCatalogStyles() for default document adoption and idempotency. Resetting document.adoptedStyleSheets = [] in afterEach (matching a2ui-lit-element.test.ts:131) and wrapping host.remove() in try/finally at lines 167-204 also avoids leaking state across tests.

🤖 Agent-generated

if (!target) return;

try {
const sheet = getDefaultStyleSheet(getOwnerDocument(target));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

getDefaultStyleSheet runs before checking Array.isArray(target.adoptedStyleSheets), constructing and parsing a CSSStyleSheet even when adoption is unavailable and the function immediately falls back to a <style> tag. Environments without adoptedStyleSheets perform wasted CSS parsing, and polyfills whose replaceSync appends a <style> to document.head (as in dom-setup.ts:92-101) leak styles into document.

-    const sheet = getDefaultStyleSheet(getOwnerDocument(target));
     const sheets = target.adoptedStyleSheets;
     if (Array.isArray(sheets)) {
+      const sheet = getDefaultStyleSheet(getOwnerDocument(target));
       if (sheets.includes(sheet)) return;
Details

Evidence (Read): typescript/core/web_core/src/universal/basic_catalog/styles/default.ts:156-158 "const sheet = getDefaultStyleSheet(getOwnerDocument(target)); const sheets = target.adoptedStyleSheets; if (Array.isArray(sheets)) {".

🤖 Agent-generated

if (sheets.includes(sheet)) return;
// In a shadow root the sheet goes first, so `:host` rules from components
// that connect later still win by source order.
target.adoptedStyleSheets = isDocument(target) ? [...sheets, sheet] : [sheet, ...sheets];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Unaddressed (open thread)] Should DEFAULT_CSS account for adoptedStyleSheets overriding <style>:host blocks in shadow roots? If Angular ViewEncapsulation.ShadowDom or Declarative Shadow DOM hosts are in scope, their internal :host overrides will be silently lost.

Details

Evidence (Deduction): typescript/core/web_core/src/universal/basic_catalog/styles/default.ts:34-49 declares :host rules at (0, 1, 0) and default.ts:162 adopts the sheet into shadowRoot.adoptedStyleSheets. Per CSSOM, adoptedStyleSheets evaluate after <style> elements in the same ShadowRoot, overwriting --a2ui-* tokens set in internal <style>:host blocks.

To settle: Decide whether internal <style>:host shadow hosts are in scope; if so, test a <style>:host { --a2ui-color-primary: #0f766e; }</style> shadow root in Chromium or note in docs/site/src/content/docs/guides/client-integration.mdx:1187 that overrides must live in outer styles or adoptedStyleSheets.

🤖 Agent-generated

…yles (a2ui-project#4279)

Use direct :host selectors, fall back to a style tag when adoption or constructable stylesheets throw, resolve the owner document and shadow root structurally, isolate JSDOM adoptedStyleSheets per shadow root, strengthen regression tests, and document Shadow DOM theming.
…4279)

Basic catalog defaults are now adopted into the shadow root and declared on
:host, so they beat values inherited from :root. Move the sample's token
overrides onto a2ui-kanban-chat so the primary button keeps its accessible
colours and the WCAG contrast e2e passes.
…yles (a2ui-project#4279)

Drop the redundant :host(.a2ui-dark/.a2ui-light) selectors, cache the default stylesheet per document, prepend the style-tag fallback in shadow roots, honor an explicit targetRoot without a global document, mark the CHANGELOG entry as breaking, and clarify the shadow root guidance.
@jihanurrahman33
jihanurrahman33 force-pushed the fix/4279-web-core-basic-catalog-shadow-styles branch from a2f6cc1 to 97793b4 Compare November 25, 2026 05:02
@gspencergoog

Copy link
Copy Markdown
Collaborator

@jihanurrahman33 Let me know when you've addressed the comments, and we can commit this.

…les (a2ui-project#4279)

- Keep the Lit shell sample's theme toggle working by setting color-scheme
  on the a2ui-shell shadow host, and document it in THEMING.md.
- Drop the top-level injectBasicCatalogStyles() call from the Lit Step 2
  snippet, since the Lit app renders into a shadow root.
- Only build the default stylesheet when adoptedStyleSheets is available.
- Test per-document stylesheet caching, the disconnected connectedCallback
  path and the no-argument injectBasicCatalogStyles() call.
- Move the BREAKING CHANGE changelog entry above the non-breaking entries.
@jihanurrahman33
jihanurrahman33 force-pushed the fix/4279-web-core-basic-catalog-shadow-styles branch from 60add7b to be8a6f5 Compare December 3, 2026 14:23
…asic-catalog-shadow-styles

# Conflicts:
#	typescript/core/web_core/src/universal/basic_catalog/styles/default.ts
@jihanurrahman33

Copy link
Copy Markdown
Contributor Author

@gspencergoog the review comments are addressed and pushed (a51a901, merged with the latest main):

  • getDefaultStyleSheet now runs only after the Array.isArray(adoptedStyleSheets) check.
  • Added tests for cross-document stylesheet caching, isConnected === false, and the no-arg injectBasicCatalogStyles() call.
  • The Lit shell sample and the Step 2 Lit docs are updated, and the changelog entry is back under Unreleased.
  • I also re-pushed the branch without the co-author trailer, which the CLA check rejected. cla/google passes now.

The thread about <style>:host blocks in shadow roots being overridden by adoptedStyleSheets is still open. Do you want that handled in this PR or in a follow-up? The Actions workflows still need approval to run on the latest commit.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: web_core basic catalog always adopts its stylesheet onto document

3 participants