Repository navigation
fix(web_core): scope basic catalog styles to target root in shadow DOM (#4279) - #4286
jihanurrahman33 wants to merge 8 commits into
Conversation
There was a problem hiding this comment.
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.
| const root = this.getRootNode(); | ||
| const targetRoot = | ||
| typeof ShadowRoot !== 'undefined' && root instanceof ShadowRoot ? root : undefined; | ||
| injectBasicCatalogStyles(targetRoot); |
There was a problem hiding this comment.
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
- When using
adoptedStyleSheetsfor component styles, provide a fallback (e.g., injecting a<style>tag) for environments where it is not supported (like JSDOM).
There was a problem hiding this comment.
Thanks @gemini-code-assist! Updated in commit 548237a:
- Replaced
root instanceof ShadowRootwith cross-realm safe detectionroot && root !== doc && ('host' in root || 'adoptedStyleSheets' in root). - Added fallback style tag injection (
<style data-a2ui-basic-catalog>) ininjectBasicCatalogStylesfor environments whereadoptedStyleSheetsis unsupported or throws, with deduplication checks. - Added unit test coverage for the fallback injection path. All 1,651 tests in web_core pass cleanly.
There was a problem hiding this comment.
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.
gspencergoog
left a comment
There was a problem hiding this comment.
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
| 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(); | ||
| }); |
There was a problem hiding this comment.
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.
| 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
| 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, | ||
| }); | ||
| } |
There was a problem hiding this comment.
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.
| 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
| :where(:root, :host), | ||
| :where(.a2ui-dark), | ||
| :where(.a2ui-light), | ||
| :where(:host(.a2ui-dark)), | ||
| :where(:host(.a2ui-light)) { |
There was a problem hiding this comment.
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
| :where(:root, :host), | ||
| :where(.a2ui-dark), | ||
| :where(.a2ui-light), | ||
| :where(:host(.a2ui-dark)), | ||
| :where(:host(.a2ui-light)) { |
There was a problem hiding this comment.
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
| 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)) { |
There was a problem hiding this comment.
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
| 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); |
There was a problem hiding this comment.
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.
| 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
| @@ -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)). | |||
There was a problem hiding this comment.
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
| 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); | ||
| } |
There was a problem hiding this comment.
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.
| 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
| 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); |
There was a problem hiding this comment.
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
548237a to
d573e47
Compare
|
@gspencergoog Thanks for the thorough review. Rebased onto main and addressed each point in d573e47:
One design call I'd like your view on: defaults stay on |
|
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. |
📖 Docs Site Preview DeployedPreview URL: https://a2ui.org/pr-preview/pr-4286/ Modified pages in this PR: Built from commit |
|
The |
0161d5c to
b5ddce1
Compare
|
The Actions workflows for the latest push are waiting for approval ( |
|
@gspencergoog friendly nudge when you have a moment. Your Two things are still open on the maintainer side: the full workflow run for |
b5ddce1 to
34cca0c
Compare
|
@gspencergoog This is rebased onto the latest |
gspencergoog
left a comment
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
: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
| ## 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)). |
There was a problem hiding this comment.
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.
| - 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); |
There was a problem hiding this comment.
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.
| 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(); |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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]; |
There was a problem hiding this comment.
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
|
@gspencergoog thanks for the second round. Pushed
I haven't tested your question about
|
gspencergoog
left a comment
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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', () => { |
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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]; |
There was a problem hiding this comment.
[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
…n basic catalog styles
…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.
a2f6cc1 to
97793b4
Compare
|
@jihanurrahman33 Let me know when you've addressed the comments, and we can commit this. |
…asic-catalog-shadow-styles
…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.
60add7b to
be8a6f5
Compare
…asic-catalog-shadow-styles # Conflicts: # typescript/core/web_core/src/universal/basic_catalog/styles/default.ts
|
@gspencergoog the review comments are addressed and pushed (
The thread about |
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()calledinjectBasicCatalogStyles()with no argument, andinjectBasicCatalogStylesunconditionally adopted the default stylesheet intodocument.adoptedStyleSheets. This leaked:where(:root) { color-scheme: light dark; }and--a2ui-*custom properties onto the host document.This PR:
injectBasicCatalogStyles(targetRoot?: Document | ShadowRoot)to adopt intotargetRoot ?? document, avoidingdocument.adoptedStyleSheetsmutation whentargetRootis aShadowRoot.BasicCatalogA2uiLitElement.connectedCallback()to passthis.getRootNode()when it is aShadowRoot.DEFAULT_CSSselectors 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.injectBasicCatalogStylesinside aShadowRootadopts into the shadow root without pollutingdocument.adoptedStyleSheets.Verification
@a2ui/web_coreunit and conformance tests (corepack yarn test), 1,650 tests passing (including new regression tests).@a2ui/littest suite, all unit and integration tests passing.@a2ui/reacttest suite, all unit and integration tests passing.