Skip to content

Commit a62578e

Browse files
committed
fix(components): name the template owner of projected @for and @defer blocks
A block that one component content-projects into another was listed with the component it was projected into, because the owner came from the anchor's parent element. Read it through ng.getOwningComponent and ng.getHostElement from the block's anchor instead, and fall back to the nearest host above the node when those utils are missing. Refs #341
1 parent df2f0dc commit a62578e

6 files changed

Lines changed: 217 additions & 29 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// @vitest-environment jsdom
2+
import { afterEach, describe, expect, it } from 'vitest';
3+
import { blockOwnerOf, type BlockOwnerDebugNg } from '../block-owner.ts';
4+
import { elementById } from '../element-id.ts';
5+
6+
class _SignalsExample {}
7+
class _ExamplePanel {}
8+
class _Card {}
9+
10+
function page() {
11+
document.body.innerHTML = `
12+
<app-root>
13+
<app-example-panel><div class="panel"><app-card></app-card></div></app-example-panel>
14+
</app-root>`;
15+
const root = document.querySelector('app-root')!;
16+
const panel = document.querySelector('app-example-panel')!;
17+
const card = document.querySelector('app-card')!;
18+
const anchor = document.createComment('container');
19+
panel.querySelector('.panel')!.appendChild(anchor);
20+
const instances = new Map<Element, object>([
21+
[root, new _SignalsExample()],
22+
[panel, new _ExamplePanel()],
23+
[card, new _Card()],
24+
]);
25+
const hosts = new Map([...instances].map(([el, instance]) => [instance, el]));
26+
return { root, panel, card, anchor, instances, hosts };
27+
}
28+
29+
describe('blockOwnerOf', () => {
30+
afterEach(() => {
31+
document.body.innerHTML = '';
32+
});
33+
34+
it('names the component that declared a projected block', () => {
35+
const { root, anchor, instances, hosts } = page();
36+
const ng: BlockOwnerDebugNg = {
37+
getComponent: (el) => instances.get(el) ?? null,
38+
getOwningComponent: (node) => (node === anchor ? instances.get(root) : null),
39+
getHostElement: (instance) => hosts.get(instance) ?? null,
40+
};
41+
const owner = blockOwnerOf(ng, anchor)!;
42+
expect(owner).toMatchObject({ name: 'SignalsExample', tag: 'app-root' });
43+
expect(elementById(owner.id)).toBe(root);
44+
expect(blockOwnerOf(ng, anchor)!.id).toBe(owner.id);
45+
});
46+
47+
it('falls back to the nearest host above the node without getOwningComponent', () => {
48+
const { anchor, instances } = page();
49+
const ng: BlockOwnerDebugNg = { getComponent: (el) => instances.get(el) ?? null };
50+
expect(blockOwnerOf(ng, anchor)).toMatchObject({ name: 'ExamplePanel' });
51+
});
52+
53+
it('falls back when the utils throw or give no host element', () => {
54+
const { anchor, instances } = page();
55+
const throwing: BlockOwnerDebugNg = {
56+
getComponent: (el) => instances.get(el) ?? null,
57+
getOwningComponent: () => {
58+
throw new Error('not in a view');
59+
},
60+
};
61+
expect(blockOwnerOf(throwing, anchor)).toMatchObject({ name: 'ExamplePanel' });
62+
const hostless: BlockOwnerDebugNg = {
63+
getComponent: (el) => instances.get(el) ?? null,
64+
getOwningComponent: () => ({}),
65+
getHostElement: () => null,
66+
};
67+
expect(blockOwnerOf(hostless, anchor)).toMatchObject({ name: 'ExamplePanel' });
68+
});
69+
70+
it('starts the fallback above a root node that is a component host', () => {
71+
const { card, instances } = page();
72+
const ng: BlockOwnerDebugNg = { getComponent: (el) => instances.get(el) ?? null };
73+
expect(blockOwnerOf(ng, card)).toMatchObject({ name: 'ExamplePanel' });
74+
expect(blockOwnerOf(ng, null)).toBeUndefined();
75+
});
76+
});

‎packages/devtools/src/__tests__/defer-blocks-real.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from '@angular/core';
99
import { bootstrapApplication } from '@angular/platform-browser';
1010
import { afterEach, describe, expect, it } from 'vitest';
11+
import { elementById } from '../element-id.ts';
1112
import { createDeferTracker, type DeferDebugNg } from '../defer-blocks.ts';
1213

1314
class TripReviews {
@@ -26,6 +27,27 @@ Component({
2627
`,
2728
})(TripReviews);
2829

30+
class ExamplePanel {}
31+
Component({
32+
selector: 'app-example-panel',
33+
template: `<div class="panel"><ng-content /></div>`,
34+
})(ExamplePanel);
35+
36+
class LazyExample {}
37+
Component({
38+
selector: 'app-root',
39+
imports: [ExamplePanel],
40+
template: `
41+
<app-example-panel>
42+
@defer (on idle) {
43+
<p>Loaded</p>
44+
} @placeholder {
45+
<p>Waiting</p>
46+
}
47+
</app-example-panel>
48+
`,
49+
})(LazyExample);
50+
2951
const settle = async (app: ApplicationRef) => {
3052
for (let i = 0; i < 5; i++) {
3153
await new Promise((resolve) => setTimeout(resolve, 0));
@@ -67,4 +89,20 @@ describe('createDeferTracker with a real app', () => {
6789
expect(loaded).toMatchObject({ id: block.id, state: 'complete' });
6890
expect(loaded.rootIds).toHaveLength(1);
6991
});
92+
93+
it('names the template owner of a @defer block projected into another component', async () => {
94+
document.body.innerHTML = '<app-root></app-root>';
95+
app = await bootstrapApplication(LazyExample, {
96+
providers: [provideZonelessChangeDetection()],
97+
});
98+
await settle(app);
99+
100+
const ng = (globalThis as { ng?: DeferDebugNg }).ng!;
101+
const tracker = createDeferTracker();
102+
const [block] = tracker.collect(ng) ?? [];
103+
expect(block).toMatchObject({ owner: { name: 'LazyExample', tag: 'app-root' } });
104+
expect(elementById(block.owner!.id)).toBe(document.querySelector('app-root'));
105+
const [again] = tracker.collect(ng) ?? [];
106+
expect(again.id).toBe(block.id);
107+
});
70108
});

‎packages/devtools/src/__tests__/for-blocks-real.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,27 @@ Component({
3838
`,
3939
})(TripList);
4040

41+
class ExamplePanel {}
42+
Component({
43+
selector: 'app-example-panel',
44+
template: `<div class="panel"><ng-content /></div>`,
45+
})(ExamplePanel);
46+
47+
class SignalsExample {
48+
readonly items = signal(['x', 'y']);
49+
}
50+
Component({
51+
selector: 'app-root',
52+
imports: [ExamplePanel],
53+
template: `
54+
<app-example-panel>
55+
@for (item of items(); track item) {
56+
<i>{{ item }}</i>
57+
}
58+
</app-example-panel>
59+
`,
60+
})(SignalsExample);
61+
4162
const settle = async (app: ApplicationRef) => {
4263
for (let i = 0; i < 5; i++) {
4364
await new Promise((resolve) => setTimeout(resolve, 0));
@@ -90,4 +111,22 @@ describe('createForTracker with a real app', () => {
90111
expect(moreTrips).toMatchObject({ id: trips.id, count: 3 });
91112
expect(someTags).toMatchObject({ id: tags.id, count: 1, showingEmpty: false });
92113
});
114+
115+
it('names the template owner of a @for block projected into another component', async () => {
116+
document.body.innerHTML = '<app-root></app-root>';
117+
app = await bootstrapApplication(SignalsExample, {
118+
providers: [provideZonelessChangeDetection()],
119+
});
120+
await settle(app);
121+
122+
const ng = (globalThis as { ng?: ControlFlowDebugNg }).ng!;
123+
const tracker = createForTracker();
124+
const [block] = tracker.collect(ng)!.forBlocks;
125+
expect(block).toMatchObject({
126+
count: 2,
127+
owner: { name: 'SignalsExample', tag: 'app-root' },
128+
});
129+
expect(elementById(block.owner!.id)).toBe(document.querySelector('app-root'));
130+
expect(tracker.collect(ng)!.forBlocks[0].id).toBe(block.id);
131+
});
93132
});
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { componentHostOf, type ComponentDebugNg } from './component-tree.ts';
2+
import { elementId } from './element-id.ts';
3+
import { className } from './injector-tree.ts';
4+
5+
export interface BlockOwnerDebugNg extends ComponentDebugNg {
6+
getOwningComponent?(node: Node): unknown;
7+
getHostElement?(instance: object): unknown;
8+
}
9+
10+
export interface BlockOwner {
11+
id: string;
12+
name: string;
13+
tag: string;
14+
}
15+
16+
function read<T>(fn: () => T, fallback: T): T {
17+
try {
18+
return fn();
19+
} catch {
20+
return fallback;
21+
}
22+
}
23+
24+
/**
25+
* The component whose template holds a control flow block, read from the
26+
* block's anchor comment or, failing that, one of its root nodes. Angular
27+
* patches each container anchor with the view that declares it.
28+
*
29+
* `ng.getOwningComponent` reads the node's own view and climbs embedded views
30+
* up to the component view that declared it (`_debug_node-chunk.mjs`), so a
31+
* block that component A content-projects into component B still names A.
32+
* `ng.getHostElement` then gives A's host. When either util is missing or
33+
* answers nothing, the nearest component host above the node stands in,
34+
* which is right for every block that is not projected. It starts at the
35+
* node's parent, so a root node that is a component host itself still names
36+
* the template it sits in.
37+
*/
38+
export function blockOwnerOf(ng: BlockOwnerDebugNg, node: Node | null): BlockOwner | undefined {
39+
if (!node) return undefined;
40+
let owner: Element | null = null;
41+
let instance: unknown = null;
42+
const owning = read(() => ng.getOwningComponent?.(node) ?? null, null);
43+
if (owning && typeof owning === 'object') {
44+
const host = read(() => ng.getHostElement?.(owning) ?? null, null);
45+
if (host instanceof Element) {
46+
owner = host;
47+
instance = owning;
48+
}
49+
}
50+
if (!owner) {
51+
const parent = node.parentElement;
52+
owner = parent ? componentHostOf(ng, parent) : null;
53+
instance = owner ? read(() => ng.getComponent?.(owner!), null) : null;
54+
}
55+
const ctor = (instance as { constructor?: unknown } | null)?.constructor;
56+
if (!owner || typeof ctor !== 'function') return undefined;
57+
return { id: elementId(owner), name: className(ctor), tag: owner.tagName.toLowerCase() };
58+
}

‎packages/devtools/src/defer-blocks.ts‎

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
import { componentHostOf, type ComponentDebugNg } from './component-tree.ts';
1+
import { blockOwnerOf, type BlockOwnerDebugNg } from './block-owner.ts';
22
import { elementId } from './element-id.ts';
33
import { angularRoots } from './host-tree.ts';
4-
import { className } from './injector-tree.ts';
54
import type { DeferBlockInfo } from './types.ts';
65

7-
export interface DeferDebugNg extends ComponentDebugNg {
6+
export interface DeferDebugNg extends BlockOwnerDebugNg {
87
ɵgetControlFlowBlocks?(node: Node): unknown[];
98
ɵgetDeferBlocks?(node: Node): unknown[];
109
}
@@ -106,15 +105,6 @@ export function createDeferTracker(now: () => number = Date.now) {
106105
return id;
107106
};
108107

109-
const ownerOf = (ng: DeferDebugNg, host: Node | null): DeferBlockInfo['owner'] => {
110-
const parent = !host ? null : host instanceof Element ? host : host.parentElement;
111-
const owner = parent ? componentHostOf(ng, parent) : null;
112-
const instance = owner ? read(() => ng.getComponent?.(owner), null) : null;
113-
const ctor = (instance as { constructor?: unknown } | null)?.constructor;
114-
if (!owner || typeof ctor !== 'function') return undefined;
115-
return { id: elementId(owner), name: className(ctor), tag: owner.tagName.toLowerCase() };
116-
};
117-
118108
return {
119109
/** True when the last `collect` stopped at {@link MAX_DEFER_BLOCKS} with blocks left. */
120110
get truncated() {
@@ -185,10 +175,7 @@ export function createDeferTracker(now: () => number = Date.now) {
185175
.slice(0, MAX_ROOT_IDS)
186176
.map((el) => elementId(el)),
187177
};
188-
const owner = ownerOf(
189-
ng,
190-
raw.hostNode instanceof Node ? raw.hostNode : (hostNode?.parentNode ?? null),
191-
);
178+
const owner = blockOwnerOf(ng, hostNode);
192179
if (owner) block.owner = owner;
193180
if (triggers.includes('hydrate never')) block.hydrateNever = true;
194181
if (raw.loadingBlock?.exists) {

‎packages/devtools/src/for-blocks.ts‎

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
import { componentHostOf, type ComponentDebugNg } from './component-tree.ts';
1+
import { blockOwnerOf, type BlockOwnerDebugNg } from './block-owner.ts';
22
import { elementId } from './element-id.ts';
33
import { angularRoots } from './host-tree.ts';
4-
import { className } from './injector-tree.ts';
54
import type { ForBlockInfo } from './types.ts';
65

7-
export interface ControlFlowDebugNg extends ComponentDebugNg {
6+
export interface ControlFlowDebugNg extends BlockOwnerDebugNg {
87
ɵgetControlFlowBlocks?(node: Node): unknown[];
98
}
109

@@ -105,15 +104,6 @@ export function createForTracker() {
105104
return (keys[index] ??= {});
106105
};
107106

108-
const ownerOf = (ng: ControlFlowDebugNg, anchor: Node | null): ForBlockInfo['owner'] => {
109-
const parent = !anchor ? null : anchor instanceof Element ? anchor : anchor.parentElement;
110-
const owner = parent ? componentHostOf(ng, parent) : null;
111-
const instance = owner ? read(() => ng.getComponent?.(owner), null) : null;
112-
const ctor = (instance as { constructor?: unknown } | null)?.constructor;
113-
if (!owner || typeof ctor !== 'function') return undefined;
114-
return { id: elementId(owner), name: className(ctor), tag: owner.tagName.toLowerCase() };
115-
};
116-
117107
return {
118108
/**
119109
* Every `@for` block on the page, or `undefined` when Angular exposes no
@@ -153,7 +143,7 @@ export function createForTracker() {
153143
.slice(0, MAX_ROOT_IDS)
154144
.map((el) => elementId(el)),
155145
};
156-
const owner = ownerOf(
146+
const owner = blockOwnerOf(
157147
ng,
158148
anchor ?? (roots.find((n) => n instanceof Node) as Node) ?? null,
159149
);

0 commit comments

Comments
 (0)