Skip to content

Commit 62d9f79

Browse files
authored
feat(overlay): explain change detection, leaks and common errors (#395)
Refs #343.
1 parent 22c8819 commit 62d9f79

68 files changed

Lines changed: 10668 additions & 198 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
import { TestBed, type ComponentFixture } from '@angular/core/testing';
2+
import type { CdDiagnosis as Diagnosis } from '@pangular-inspector/devtools/config';
3+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
4+
import { CdDiagnosis } from '../pages/cd-diagnosis';
5+
import { CdRecording, type CdPage } from '../pages/cd-recording';
6+
7+
const diagnosis: Diagnosis = {
8+
triggers: true,
9+
waste: true,
10+
major: 22,
11+
causes: { signal: 4, event: 2, zone: 1 },
12+
components: [
13+
{ name: 'Banner', refreshed: 20, unchanged: 19, strategy: 'Eager' },
14+
{ name: 'Cart', refreshed: 5, unchanged: 0, strategy: 'OnPush' },
15+
],
16+
inputs: [{ name: 'Row', input: 'items', parent: 'List', inPlace: 3, sameContents: 1 }],
17+
zone: [{ name: 'Clock', ticks: 1, tasks: ['setTimeout'] }],
18+
};
19+
20+
function page(extra: Partial<CdPage> = {}): CdPage {
21+
return {
22+
pageId: 'p1',
23+
supported: true,
24+
recording: false,
25+
startedAt: 1000,
26+
dropped: 0,
27+
cycles: [
28+
{
29+
id: 1,
30+
at: 1001,
31+
ms: 1,
32+
passes: 1,
33+
checks: 2,
34+
components: [{ name: 'Cart', checks: 1, ms: 0.5 }],
35+
trigger: 'Cart (add)',
36+
cause: {
37+
kind: 'event',
38+
event: 'click',
39+
target: 'button',
40+
component: 'Cart',
41+
listener: 'add',
42+
},
43+
refreshed: 2,
44+
unchanged: 1,
45+
},
46+
],
47+
components: [{ name: 'Cart', checks: 2, ms: 1, maxMs: 1, cycles: 1 }],
48+
hosts: {},
49+
diagnosis,
50+
...extra,
51+
};
52+
}
53+
54+
const text = (el: Element | null) => el?.textContent?.replace(/\s+/g, ' ').trim() ?? '';
55+
/** A table row's cells, joined with spaces. */
56+
const cells = (row: Element | null) =>
57+
[...(row?.querySelectorAll('td') ?? [])].map((cell) => text(cell)).join(' ');
58+
59+
describe('CdDiagnosis', () => {
60+
let fixture: ComponentFixture<CdDiagnosis>;
61+
const host = () => fixture.nativeElement as HTMLElement;
62+
const section = (heading: string) =>
63+
[...host().querySelectorAll('h4')].find((h) => text(h) === heading)?.nextElementSibling ?? null;
64+
65+
beforeEach(() => {
66+
fixture = TestBed.createComponent(CdDiagnosis);
67+
});
68+
69+
afterEach(() => {
70+
fixture.destroy();
71+
TestBed.resetTestingModule();
72+
});
73+
74+
async function show(value: CdPage | null) {
75+
fixture.componentRef.setInput('page', value);
76+
await fixture.whenStable();
77+
}
78+
79+
it('shows nothing for a recording without a diagnosis', async () => {
80+
await show(page({ diagnosis: undefined }));
81+
expect(host().querySelector('section')).toBeNull();
82+
});
83+
84+
it('lists causes in a fixed order, zone.js dependents, wasted checks, inputs and hints', async () => {
85+
await show(page());
86+
const heading = host().querySelector('section')!.getAttribute('aria-labelledby')!;
87+
expect(text(host().querySelector(`#${heading}`))).toBe('Why it ran and what it wasted');
88+
const causes = [...section('What started the cycles')!.querySelectorAll('tbody tr')].map(cells);
89+
expect(causes).toEqual(['Event 2', 'Signal write 4', 'zone.js only 1']);
90+
expect(cells(section('Depends on zone.js')!.querySelector('tbody tr'))).toBe(
91+
'Clock 1 setTimeout',
92+
);
93+
const wasted = [...section('Wasted checks')!.querySelectorAll('tbody tr')].map(cells);
94+
expect(wasted).toEqual(['Banner 20 19 (95%) Eager']);
95+
expect(cells(section('Inputs that break OnPush')!.querySelector('tbody tr'))).toBe(
96+
'Row.items List 3 1',
97+
);
98+
const hints = [...section('Hints')!.querySelectorAll('li')].map(text);
99+
expect(hints[0]).toContain('Banner was refreshed 20 times and changed something in 1');
100+
expect(hints[0]).toContain('default from Angular 22');
101+
expect(
102+
hints.some((h) => h.includes('Input items of Row set by List changed in place 3 times')),
103+
).toBe(true);
104+
expect(
105+
hints.some((h) => h.startsWith('Clock changed in 1 tick that only zone.js started')),
106+
).toBe(true);
107+
});
108+
109+
it('says why causes or wasted checks are missing', async () => {
110+
await show(
111+
page({ diagnosis: { ...diagnosis, triggers: false, waste: false, zone: undefined } }),
112+
);
113+
expect(text(section('What started the cycles'))).toContain('needs Angular 18 or later');
114+
expect(text(section('Wasted checks'))).toContain("can't watch DOM updates");
115+
expect(section('Depends on zone.js')).toBeNull();
116+
});
117+
118+
it('says when zone.js ticks changed nothing', async () => {
119+
await show(page({ diagnosis: { ...diagnosis, zone: undefined } }));
120+
expect(text(section('Depends on zone.js'))).toBe(
121+
'1 tick came from zone.js alone, and no component changed in them.',
122+
);
123+
});
124+
});
125+
126+
describe('CdDiagnosis and the zoneJs flag', () => {
127+
afterEach(() => TestBed.resetTestingModule());
128+
129+
async function zoneSection(zoneJs: boolean) {
130+
const fixture = TestBed.createComponent(CdDiagnosis);
131+
fixture.componentRef.setInput(
132+
'page',
133+
page({ diagnosis: { ...diagnosis, causes: { signal: 4 }, zone: [], zoneJs } }),
134+
);
135+
await fixture.whenStable();
136+
const h4 = [...(fixture.nativeElement as HTMLElement).querySelectorAll('h4')].find(
137+
(h) => h.textContent?.trim() === 'Depends on zone.js',
138+
);
139+
return h4?.parentElement ?? null;
140+
}
141+
142+
it('shows the zone.js block on a zone.js page even when zone.js started no tick', async () => {
143+
expect((await zoneSection(true))?.textContent).toContain(
144+
'No component changed in a tick only zone.js started.',
145+
);
146+
});
147+
148+
it('hides it on a zoneless page', async () => {
149+
expect(await zoneSection(false)).toBeNull();
150+
});
151+
});
152+
153+
describe('CdDiagnosis on a zoneless page', () => {
154+
afterEach(() => TestBed.resetTestingModule());
155+
156+
it('hides the zone.js block when no tick came from zone.js', async () => {
157+
const fixture = TestBed.createComponent(CdDiagnosis);
158+
fixture.componentRef.setInput(
159+
'page',
160+
page({ diagnosis: { ...diagnosis, causes: { signal: 4, event: 2 }, zone: [] } }),
161+
);
162+
await fixture.whenStable();
163+
const host = fixture.nativeElement as HTMLElement;
164+
const headings = [...host.querySelectorAll('h4')].map((h) => text(h));
165+
expect(headings).toContain('What started the cycles');
166+
expect(headings).not.toContain('Depends on zone.js');
167+
expect(host.textContent).not.toContain('zone.js started');
168+
fixture.destroy();
169+
});
170+
});
171+
172+
describe('CdRecording latest cycles', () => {
173+
it('names what started a cycle and how many checks changed nothing', async () => {
174+
const fixture = TestBed.createComponent(CdRecording);
175+
fixture.componentRef.setInput('page', page());
176+
await fixture.whenStable();
177+
const row = (fixture.nativeElement as HTMLElement).querySelector('.cycles li');
178+
expect(text(row)).toContain('from click on button in Cart (add)');
179+
expect(text(row)).toContain('1 changed nothing');
180+
expect(text(row)).not.toContain('after Cart (add)');
181+
expect(
182+
(fixture.nativeElement as HTMLElement).querySelector('app-cd-diagnosis section'),
183+
).not.toBeNull();
184+
fixture.destroy();
185+
TestBed.resetTestingModule();
186+
});
187+
});
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import { TestBed } from '@angular/core/testing';
2+
import { By } from '@angular/platform-browser';
3+
import type { DevframeRpcClient } from 'devframe/client';
4+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5+
import { ComponentTree } from '../pages/component-tree';
6+
import type { TreeNode } from '../pages/component-tree-state';
7+
import { LeaksSection } from '../pages/leaks-section';
8+
import { keepBelowSticky, scrollParent, stickyClearance } from '../ui/sticky-clearance';
9+
10+
const roots: TreeNode[] = [
11+
{
12+
id: 'c1',
13+
name: 'App',
14+
tag: 'app-root',
15+
children: [
16+
{
17+
id: 'c2',
18+
name: 'TripList',
19+
tag: 'app-trip-list',
20+
children: [{ id: 'c3', name: 'TripCard', tag: 'app-trip-card', children: [] }],
21+
},
22+
],
23+
},
24+
];
25+
26+
function client() {
27+
const rpc = {
28+
call: () => Promise.resolve([]),
29+
callEvent: () => Promise.resolve(),
30+
sharedState: (name: string) =>
31+
Promise.resolve({
32+
value: () =>
33+
name === 'component-tree'
34+
? { pages: { p1: { pageId: 'p1', roots, count: 3, detail: null, reportedAt: 1000 } } }
35+
: null,
36+
on: () => () => {},
37+
}),
38+
};
39+
return { connectionMeta: {}, scope: () => ({ rpc }) } as unknown as DevframeRpcClient;
40+
}
41+
42+
describe('component tree and the Leaks section', () => {
43+
beforeEach(() => {
44+
vi.stubGlobal('CSS', { escape: (value: string) => value });
45+
Element.prototype.scrollIntoView ??= () => {};
46+
});
47+
afterEach(() => {
48+
vi.unstubAllGlobals();
49+
document.body.innerHTML = '';
50+
TestBed.resetTestingModule();
51+
});
52+
53+
it('moves focus to the tree row of a Leaks row and keeps it clear of the toolbar', async () => {
54+
const fixture = TestBed.createComponent(ComponentTree);
55+
fixture.componentRef.setInput('rpc', client());
56+
// The panel's scroller: the toolbar sticks inside its padding.
57+
const main = document.createElement('main');
58+
main.style.overflowY = 'auto';
59+
main.style.paddingTop = '20px';
60+
main.append(fixture.nativeElement);
61+
document.body.append(main);
62+
for (let i = 0; i < 3; i++) {
63+
await new Promise((resolve) => setTimeout(resolve));
64+
await fixture.whenStable();
65+
}
66+
const el = fixture.nativeElement as HTMLElement;
67+
Object.defineProperty(el.querySelector('.toolbar')!, 'offsetHeight', { value: 64 });
68+
const scrolled = vi.spyOn(Element.prototype, 'scrollIntoView');
69+
const leaks = fixture.debugElement.query(By.directive(LeaksSection));
70+
expect(leaks).not.toBeNull();
71+
(leaks.componentInstance as LeaksSection).showComponent.emit('c3');
72+
fixture.detectChanges();
73+
await fixture.whenStable();
74+
const row = el.querySelector<HTMLElement>('.row[data-id="c3"]')!;
75+
expect(row.getAttribute('aria-selected')).toBe('true');
76+
expect(document.activeElement).toBe(row);
77+
expect(scrolled).toHaveBeenCalled();
78+
// The scroller's padding, the toolbar's height and an 8px gap.
79+
expect(el.style.getPropertyValue('--ct-toolbar-clearance')).toBe('92px');
80+
});
81+
82+
it('measures the clearance a sticky bar needs, with the scroller padding and scroll padding', () => {
83+
const scroller = document.createElement('div');
84+
scroller.style.overflowY = 'auto';
85+
scroller.style.paddingTop = '16px';
86+
const wrap = document.createElement('section');
87+
const bar = document.createElement('div');
88+
bar.style.top = '4px';
89+
Object.defineProperty(bar, 'offsetHeight', { value: 100 });
90+
wrap.append(bar);
91+
scroller.append(wrap);
92+
document.body.append(scroller);
93+
expect(scrollParent(bar)).toBe(scroller);
94+
expect(stickyClearance(bar)).toBe(16 + 4 + 100 + 8);
95+
scroller.style.scrollPaddingTop = '10px';
96+
expect(stickyClearance(bar, 0)).toBe(16 + 4 + 100 - 10);
97+
// Without a scrolling ancestor the page scrolls, with no padding to add.
98+
const loose = document.createElement('div');
99+
Object.defineProperty(loose, 'offsetHeight', { value: 50 });
100+
document.body.append(loose);
101+
expect(scrollParent(loose)).toBeNull();
102+
expect(stickyClearance(loose)).toBe(58);
103+
});
104+
105+
it('scrolls a row the sticky bar covers back below it, and leaves a clear row alone', () => {
106+
const scroller = document.createElement('div');
107+
scroller.style.overflowY = 'auto';
108+
const bar = document.createElement('div');
109+
const row = document.createElement('div');
110+
scroller.append(bar, row);
111+
document.body.append(scroller);
112+
scroller.scrollTop = 400;
113+
const rect = (top: number, bottom: number) => ({ top, bottom }) as DOMRect;
114+
bar.getBoundingClientRect = () => rect(65, 117);
115+
row.getBoundingClientRect = () => rect(92, 124);
116+
keepBelowSticky(row, bar);
117+
// 117 + 8 - 92: the row moves 33px down.
118+
expect(scroller.scrollTop).toBe(367);
119+
row.getBoundingClientRect = () => rect(130, 162);
120+
keepBelowSticky(row, bar);
121+
expect(scroller.scrollTop).toBe(367);
122+
});
123+
});

0 commit comments

Comments
 (0)