Skip to content

Commit 7be54df

Browse files
authored
fix(angular): resolve universal element injectors per renderer (#4129)
### Summary With `useUniversalComponents`, every catalog entry renders as a custom element that looks up the Angular `Injector` it needs when it connects. This PR fixes that lookup for pages with more than one renderer, and lets plain `{...api, component}` entries render inside universal containers. An `AngularWcHost` now takes its own `injector` first. Then it tries the nearest `ComponentHostComponent` above it in the DOM, then the `A2uiRendererService` that owns its surface, and finally a stack of fallback injectors. Destroying one renderer no longer clears the fallback of another. **Breaking:** with `useUniversalComponents: true`, plain `{...api, component}` entries now mount inside an `<a2ui-ng-<name>>` host element. ### Changes - `AngularCatalog` adds `tagName` and `element` to plain `{...api, component}` entries, so universal containers can render them. Extensible entries are updated in place to keep their identity. - `AngularWcHost` resolves its injector from the DOM host, then the surface group, then the fallback stack. `ComponentHostComponent` and `A2uiRendererService` register their injectors for this lookup. - `A2uiLitElement.adoptLightDomStyles` caches scoped styles per element class instead of in inherited static fields, so a subclass registered under another tag gets its own sheet. ### Verification - `yarn --cwd typescript/core/web_core test` and the Angular karma suite (`ng test lib`), with the new specs confirmed in the karma output. - `yarn lint` in both packages, the web_core and Angular builds, and `./scripts/fix_format.sh --check`. Part of #4148.
1 parent de13698 commit 7be54df

11 files changed

Lines changed: 446 additions & 46 deletions

File tree

‎typescript/core/web_core/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
- (v1_0) Function calls inside `${...}` template expressions of `formatString` now inherit the `catalogId` that the enclosing `formatString` call resolved to (preserving reserved `@`-prefixed system calls such as `${@index()}` as catalogless), so nested template calls resolve against `formatString`'s catalog on defaultless surfaces and when the surface defines a different default `catalogId` ([#3727](https://github.com/a2ui-project/a2ui/issues/3727), [#4028](https://github.com/a2ui-project/a2ui/pull/4028)).
4141
- `extractRefFields`, `NodeResolver`, `GenericBinder`, `scrapeSchemaBehavior`, `scrapeComponentBehavior` (newly exported), and `Catalog.componentRefMap` now resolve child references and dynamic bindings across wrapped (`ZodCatch`, `ZodPipeline`), composite (`ZodIntersection`, `ZodUnion`, `ZodDiscriminatedUnion`), empty-shape (`z.object({})`), open (`.passthrough()`, `.catchall()`, `z.record()`, `z.any()`, `z.unknown()`), and unannotated `child` / `children` component schemas ([#3783](https://github.com/a2ui-project/a2ui/issues/3783), [#3938](https://github.com/a2ui-project/a2ui/pull/3938)).
4242
- Export `getMarkdownRenderer`, `markdown`, and `setMarkdownRenderer` from `@a2ui/web_core/universal`, make `Catalog<T, F>` covariant in `T` and `F`, and infer `T` from the `catalogs` argument of `new MessageProcessor(catalogs)` so `SurfaceModel` instances carry the component implementation type of their registered catalogs ([#3423](https://github.com/a2ui-project/a2ui/issues/3423), [#4181](https://github.com/a2ui-project/a2ui/pull/4181)).
43+
- `A2uiLitElement.adoptLightDomStyles` scopes styles per element class, so a subclass registered under another tag gets its own stylesheet instead of reusing its parent's. [#4129](https://github.com/a2ui-project/a2ui/pull/4129)
4344

4445
## 0.15.0
4546

‎typescript/core/web_core/src/universal/a2ui-lit-element.test.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,9 +157,32 @@ describe('A2uiLitElement', () => {
157157

158158
assert.strictEqual(el.renderRoot, el);
159159
assert.strictEqual(el.shadowRoot, null);
160-
assert.ok((TestLightStyledElement as any)._processedCss?.includes('test-light-styled-element'));
161-
assert.ok((TestLightStyledElement as any)._adoptedRoots?.has(document));
162160
assert.strictEqual(document.adoptedStyleSheets.length, 1);
161+
162+
// A second element of the same class reuses the adopted sheet.
163+
document.body.appendChild(document.createElement('test-light-styled-element'));
164+
assert.strictEqual(document.adoptedStyleSheets.length, 1);
165+
});
166+
167+
it('adopts a separate scoped sheet for a subclass registered under another tag', () => {
168+
class TestBaseStyledElement extends A2uiLitElement<any> {
169+
static override styles = css`
170+
.title {
171+
color: green;
172+
}
173+
`;
174+
override createController() {
175+
return {dispose: () => {}} as any;
176+
}
177+
}
178+
class TestDerivedStyledElement extends TestBaseStyledElement {}
179+
customElements.define('test-base-styled-element', TestBaseStyledElement);
180+
customElements.define('test-derived-styled-element', TestDerivedStyledElement);
181+
182+
document.body.appendChild(document.createElement('test-base-styled-element'));
183+
document.body.appendChild(document.createElement('test-derived-styled-element'));
184+
185+
assert.strictEqual(document.adoptedStyleSheets.length, 2);
163186
});
164187

165188
it('does not adopt its styles into the document when it renders into a ShadowRoot', () => {
@@ -184,7 +207,6 @@ describe('A2uiLitElement', () => {
184207

185208
assert.ok(el.renderRoot instanceof (globalThis as any).ShadowRoot);
186209
assert.deepStrictEqual(document.adoptedStyleSheets, sheetsBefore);
187-
assert.strictEqual((TestShadowStyledElement as any)._processedCss, undefined);
188210
});
189211

190212
it('should create controller when context is set', async () => {

‎typescript/core/web_core/src/universal/a2ui-lit-element.ts‎

Lines changed: 32 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,18 @@ import type {WebComponentImplementation} from './web_component_implementation.js
4747

4848
export type {CheckableResolvedProps, ResolvedAccessibilityAttributes};
4949

50+
interface LightDomStyleCacheEntry {
51+
processedSheet?: CSSStyleSheet;
52+
processedCss: string;
53+
processedStyle: CSSResult;
54+
adoptedRoots: WeakSet<Node>;
55+
}
56+
57+
// Scoped styles per element class. Keyed by the class itself rather than stored as static fields
58+
// on it, because static fields are inherited: a subclass registered under another tag would reuse
59+
// the parent's sheet, which is scoped to the parent's tag and never matches the subclass.
60+
const lightDomStyleCache = new WeakMap<Function, LightDomStyleCacheEntry>();
61+
5062
/** The surface a child renders on, as its data context reports it. */
5163
type ChildSurface = NonNullable<ComponentContext['dataContext']['surface']>;
5264

@@ -241,18 +253,14 @@ export abstract class A2uiLitElement<
241253
if (this.renderRoot !== this) return;
242254
const root = this.getRootNode() as Document | ShadowRoot;
243255

244-
const constructor = this.constructor as typeof A2uiLitElement & {
245-
_processedSheet?: CSSStyleSheet;
246-
_processedCss?: string;
247-
_processedStyle?: CSSResult;
248-
_adoptedRoots?: WeakSet<Node>;
249-
};
250-
const styles = (constructor as any).styles;
256+
const constructor = this.constructor;
257+
const styles = (constructor as unknown as {styles?: unknown}).styles;
251258
if (!styles) return;
252259

253260
const tagName = this.tagName.toLowerCase();
254261

255-
if (!constructor._processedSheet && constructor._processedCss === undefined) {
262+
let cacheEntry = lightDomStyleCache.get(constructor);
263+
if (!cacheEntry) {
256264
const styleList = Array.isArray(styles) ? styles : [styles];
257265
const rawCss = styleList
258266
.map(s =>
@@ -268,6 +276,7 @@ export abstract class A2uiLitElement<
268276
.replace(/:host/g, tagName);
269277

270278
let processedCss = baseCss;
279+
let processedSheet: CSSStyleSheet | undefined;
271280

272281
try {
273282
const sheet = new CSSStyleSheet();
@@ -306,14 +315,18 @@ export abstract class A2uiLitElement<
306315
processedCss = Array.from(sheet.cssRules).map(scopeRule).join('\n');
307316
const scopedSheet = new CSSStyleSheet();
308317
scopedSheet.replaceSync(processedCss);
309-
constructor._processedSheet = scopedSheet;
318+
processedSheet = scopedSheet;
310319
} catch {
311320
// Fallback for environments lacking CSSStyleSheet support
312321
}
313322

314-
constructor._processedCss = processedCss;
315-
constructor._processedStyle = css([processedCss] as unknown as TemplateStringsArray);
316-
constructor._adoptedRoots = new WeakSet();
323+
cacheEntry = {
324+
processedSheet,
325+
processedCss,
326+
processedStyle: css([processedCss] as unknown as TemplateStringsArray),
327+
adoptedRoots: new WeakSet(),
328+
};
329+
lightDomStyleCache.set(constructor, cacheEntry);
317330
}
318331

319332
const target =
@@ -323,18 +336,13 @@ export abstract class A2uiLitElement<
323336
? document
324337
: undefined;
325338

326-
if (target) {
327-
if (!constructor._adoptedRoots) {
328-
constructor._adoptedRoots = new WeakSet();
329-
}
330-
if (!constructor._adoptedRoots.has(target)) {
331-
constructor._adoptedRoots.add(target);
332-
if (constructor._processedSheet && (target as any).adoptedStyleSheets) {
333-
(target as any).adoptedStyleSheets = [
334-
...(target as any).adoptedStyleSheets,
335-
constructor._processedSheet,
336-
];
337-
}
339+
if (target && !cacheEntry.adoptedRoots.has(target)) {
340+
cacheEntry.adoptedRoots.add(target);
341+
if (cacheEntry.processedSheet && (target as any).adoptedStyleSheets) {
342+
(target as any).adoptedStyleSheets = [
343+
...(target as any).adoptedStyleSheets,
344+
cacheEntry.processedSheet,
345+
];
338346
}
339347
}
340348
}

‎typescript/renderers/angular/CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
- **BREAKING CHANGE**: `ComponentHostComponent` no longer assigns `element.context` when mounting universal Web Components, and `ComponentBinder.bind(context)` and `AngularWcHost.context` are deprecated in favor of `ComponentBinder.bindNode(node)` and `AngularWcHost.node`. Recommended migration: implement `node` on custom `A2uiWebComponentElement` classes instead of `context`. [#3841](https://github.com/a2ui-project/a2ui/pull/3841)
44
- **BREAKING CHANGE**: The host element of an Angular catalog component (`<a2ui-v09-component-host>`, or `<a2ui-ng-<name>>` from `toWebComponent`) applies the component's `accessibility` attributes: `aria-live`, `aria-hidden`, and `inert` on the host, and `aria-label` and `aria-description` on the host with `role="group"` (unless the host already has a `role`). Add `AccessibilityTargetDirective` (`a2uiAccessibilityTarget`), which moves `aria-label` and `aria-description` to the element it marks and adds `aria-invalid="true"` there while a check fails, and `ValidationErrorsDirective` (`a2uiValidationErrors`), which marks the element showing the validation errors so the target gets `aria-describedby` pointing at it. The v0.9 native basic catalog marks the control of `Button`, `CheckBox`, `Slider`, `TextField`, `Image`, `AudioPlayer`, and `Video`, and wraps the error messages of `Slider` and `TextField` in `<div class="a2ui-validation-errors">`. Recommended migration: a component that already sets `aria-label` from `props().accessibility` on an inner element should mark that element with `a2uiAccessibilityTarget`, or the label is announced twice. [#3499](https://github.com/a2ui-project/a2ui/issues/3499), [#3869](https://github.com/a2ui-project/a2ui/pull/3869)
5+
- **BREAKING CHANGE**: With `useUniversalComponents: true`, plain `{...api, component}` catalog entries now mount inside an `<a2ui-ng-<name>>` host element, as `createComponentImplementation` entries already do. Recommended migration: update styles and selectors that expect the component as a direct child of `<a2ui-v09-component-host>`. [#4129](https://github.com/a2ui-project/a2ui/pull/4129)
56
- `ListComponent` hides the item of a child that renders nothing, so it leaves no empty marker or gap. `<a2ui-v09-component-host>` carries `data-a2ui-empty` while it renders nothing. [#2013](https://github.com/a2ui-project/a2ui/issues/2013)
67
- Import core and universal symbols from `@a2ui/web_core` and `@a2ui/web_core/universal` instead of `@a2ui/web_core/v0_9/*` across `@a2ui/angular`'s version-agnostic `core/` and `catalog/` runtime, and strip both v0.9 (`{path}`, `{call}`) and v1.0 (`{'@path'}`, `{'@call'}`) dynamic AST branches in `ComponentApiToProps`. [#4182](https://github.com/a2ui-project/a2ui/pull/4182)
8+
- `AngularCatalog` adds `tagName` and `element` to plain `{...api, component}` entries in place, keeping entry identity. Universal elements now resolve their Angular `Injector` from the nearest `ComponentHostComponent`, then from the `A2uiRendererService` owning their surface, so several renderers can share a page. [#4129](https://github.com/a2ui-project/a2ui/pull/4129)
79

810
## 0.14.0
911

‎typescript/renderers/angular/src/catalog/angular_wc_host.ts‎

Lines changed: 97 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,13 @@ import {
2222
ComponentRef,
2323
NgZone,
2424
} from '@angular/core';
25-
import {ComponentContext, type ComponentNode, effect, getValue} from '@a2ui/web_core';
25+
import {
26+
ComponentContext,
27+
type ComponentNode,
28+
type SurfaceGroupModel,
29+
effect,
30+
getValue,
31+
} from '@a2ui/web_core';
2632
import {
2733
type AccessibilityTargets,
2834
bindHostAccessibility,
@@ -34,34 +40,110 @@ import {A2UI_ACCESSIBILITY_TARGETS} from '../core/accessibility';
3440
import {ComponentBinder} from '../core/component-binder.service';
3541
import type {BoundProperty} from '../core/types';
3642

37-
let defaultInjector: Injector | undefined;
43+
const activeInjectors: Injector[] = [];
44+
const hostInjectors = new WeakMap<Node, Injector>();
45+
const surfaceGroupInjectors = new Map<
46+
SurfaceGroupModel<AngularComponentImplementation>,
47+
Injector
48+
>();
3849

3950
/**
4051
* Sets the Angular `Injector` used by wrapped Angular components whose host element was not
41-
* given one explicitly.
52+
* given one explicitly and cannot resolve one from a DOM ancestor or `SurfaceGroupModel`.
4253
*
4354
* Wrapped components are created at catalog definition time, before any injector exists, so the
4455
* injector is resolved when the element connects: the element's own `injector` property wins
45-
* (the Angular `ComponentHostComponent` sets it on the elements it mounts), and this default is
46-
* the fallback for elements created by universal container components. `A2uiRendererService`
47-
* registers its injector here on construction.
56+
* (the Angular `ComponentHostComponent` sets it on the elements it mounts), followed by the
57+
* nearest registered DOM host ancestor, the `SurfaceGroupModel` owning the surface, and finally
58+
* the most recently registered active injector.
4859
*
49-
* @param injector The injector to use as a fallback, or `undefined` to clear it.
60+
* @param injector The injector to use as a fallback, or `undefined` to clear all fallback injectors.
5061
*/
5162
export function setDefaultUniversalInjector(injector: Injector | undefined): void {
52-
defaultInjector = injector;
63+
if (!injector) {
64+
activeInjectors.length = 0;
65+
return;
66+
}
67+
const existingIndex = activeInjectors.indexOf(injector);
68+
if (existingIndex !== -1) {
69+
activeInjectors.splice(existingIndex, 1);
70+
}
71+
activeInjectors.push(injector);
5372
}
5473

5574
/**
56-
* Clears the default injector if it is still `injector`, so that a destroyed injector is not
57-
* handed to elements connected later.
75+
* Removes `injector` from the active fallback injector stack so that a destroyed injector is not
76+
* handed to elements connected later while preserving other live renderer injectors.
5877
*/
5978
export function clearDefaultUniversalInjector(injector: Injector): void {
60-
if (defaultInjector === injector) {
61-
defaultInjector = undefined;
79+
const index = activeInjectors.indexOf(injector);
80+
if (index !== -1) {
81+
activeInjectors.splice(index, 1);
82+
}
83+
}
84+
85+
/**
86+
* Associates a DOM host node (such as `ComponentHostComponent`'s host element) with its Angular
87+
* `Injector` so descendant universal elements can discover their enclosing component-tree injector.
88+
*
89+
* @param injector The host's injector, or `undefined` to drop the association.
90+
*/
91+
export function registerUniversalHostInjector(host: Node, injector: Injector | undefined): void {
92+
if (injector) {
93+
hostInjectors.set(host, injector);
94+
} else {
95+
hostInjectors.delete(host);
96+
}
97+
}
98+
99+
/**
100+
* Associates an `A2uiRendererService`'s `SurfaceGroupModel` with its Angular `Injector` so
101+
* universal elements can resolve the owning renderer's injector even when detached from a host.
102+
*
103+
* @param injector The renderer's injector, or `undefined` to drop the association.
104+
*/
105+
export function registerSurfaceGroupInjector(
106+
group: SurfaceGroupModel<AngularComponentImplementation>,
107+
injector: Injector | undefined,
108+
): void {
109+
if (injector) {
110+
surfaceGroupInjectors.set(group, injector);
111+
} else {
112+
surfaceGroupInjectors.delete(group);
62113
}
63114
}
64115

116+
/**
117+
* Resolves the Angular `Injector` for a universal custom element from its DOM ancestry, its
118+
* owning `SurfaceGroupModel`, or the active fallback injector stack.
119+
*/
120+
export function resolveUniversalInjector(
121+
node: Node | null,
122+
context?: ComponentContext,
123+
): Injector | undefined {
124+
let current: Node | null = node;
125+
while (current) {
126+
const hostInjector = hostInjectors.get(current);
127+
if (hostInjector) {
128+
return hostInjector;
129+
}
130+
current =
131+
current.parentNode ??
132+
(typeof ShadowRoot !== 'undefined' && current instanceof ShadowRoot ? current.host : null);
133+
}
134+
135+
const surface = context?.dataContext.surface;
136+
if (surface) {
137+
for (const [group, groupInjector] of surfaceGroupInjectors) {
138+
if (group.getSurface(surface.id) === surface) {
139+
return groupInjector;
140+
}
141+
}
142+
}
143+
144+
return activeInjectors[activeInjectors.length - 1];
145+
}
146+
65147
/**
66148
* Custom Element host that mounts and manages the lifecycle of an Angular component inside the
67149
* DOM for universal A2UI rendering.
@@ -98,7 +180,7 @@ export class AngularWcHost extends HTMLElement {
98180
}
99181

100182
get injector(): Injector | undefined {
101-
return this._injector ?? defaultInjector;
183+
return this._injector ?? resolveUniversalInjector(this.parentNode, this._context);
102184
}
103185

104186
connectedCallback() {
@@ -113,6 +195,7 @@ export class AngularWcHost extends HTMLElement {
113195
`'provideA2Ui'.`,
114196
);
115197
}
198+
registerUniversalHostInjector(this, injector);
116199
const node = this._node;
117200
const context = this._context;
118201
if (!node && !context) {
@@ -295,6 +378,7 @@ export class AngularWcHost extends HTMLElement {
295378
}
296379

297380
disconnectedCallback() {
381+
registerUniversalHostInjector(this, undefined);
298382
this.unbindAccessibility();
299383
this.contextSubscription?.unsubscribe();
300384
this.contextSubscription = undefined;

0 commit comments

Comments
 (0)