Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions app/src/__tests__/component-tree-source-guess.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { TestBed, type ComponentFixture } from '@angular/core/testing';
import type { DevframeRpcClient } from 'devframe/client';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { ExtensionBridge } from '../extension-bridge';
import { ComponentTree } from '../pages/component-tree';

const root = { id: 'c1', name: 'Card', tag: 'app-card', children: [] };

function detail(source?: { file: string; line: number }) {
return {
id: 'c1',
name: 'Card',
tag: 'app-card',
path: 'app-card',
...(source ? { source } : {}),
inputs: [],
outputs: [],
properties: [],
listeners: [],
directives: [],
dependencies: [],
};
}

function scanned(file: string, selector: string, line = 5) {
return {
selector,
className: 'Card',
kind: 'component',
file,
line,
inputs: [],
outputs: [],
isStandalone: true,
};
}

function fakeClient(pages: Record<string, unknown>, components: unknown[]): DevframeRpcClient {
const rpc = {
call: (name: string) => Promise.resolve(name === 'get-components' ? components : []),
callEvent: () => Promise.resolve(),
sharedState: (name: string) =>
Promise.resolve({
value: () => (name === 'component-tree' ? { pages } : null),
on: () => () => {},
}),
};
return { connectionMeta: {}, scope: () => ({ rpc }) } as unknown as DevframeRpcClient;
}

const bridge = {
available: true,
reveal: vi.fn(async () => ({ ok: true })),
openSource: vi.fn(async () => ({ ok: true })),
};

async function settle(fixture: ComponentFixture<unknown>) {
for (let i = 0; i < 3; i++) {
await new Promise((resolve) => setTimeout(resolve));
await fixture.whenStable();
}
}

async function render(components: unknown[], source?: { file: string; line: number }) {
TestBed.configureTestingModule({ providers: [{ provide: ExtensionBridge, useValue: bridge }] });
const fixture = TestBed.createComponent(ComponentTree);
fixture.componentRef.setInput(
'rpc',
fakeClient(
{
p1: { pageId: 'p1', roots: [root], count: 1, detail: detail(source), reportedAt: 1000 },
},
components,
),
);
await settle(fixture);
if (fixture.componentInstance.selectedId() !== 'c1') fixture.componentInstance.select('c1');
await settle(fixture);
return fixture;
}

function head(fixture: ComponentFixture<unknown>): HTMLElement {
return (fixture.nativeElement as HTMLElement).querySelector('.detail-head')!;
}

function text(element: Element | null | undefined) {
return (element?.textContent ?? '').replace(/\s+/g, ' ').trim();
}

function openSourceButton(fixture: ComponentFixture<unknown>) {
return [...head(fixture).querySelectorAll('button')].find(
(b) => b.textContent?.trim() === 'Open source',
)!;
}

describe('Component source location without debug info', () => {
afterEach(() => {
TestBed.resetTestingModule();
bridge.openSource.mockClear();
document.body.innerHTML = '';
});

it('shows the exact location from the page without a guess label', async () => {
const fixture = await render([scanned('src/app/other/card.ts', 'app-other')], {
file: 'src/app/card.ts',
line: 12,
});
const where = head(fixture).querySelector('.where.mono');
expect(text(where)).toBe('src/app/card.ts:12');
expect(head(fixture).querySelector('.likely')).toBeNull();
});

it('prefers the class whose selector is the host tag and marks it as likely', async () => {
const fixture = await render([
scanned('src/app/other/card.ts', 'app-other', 3),
scanned('src/app/card.ts', 'app-card', 8),
]);
const where = head(fixture).querySelector('.where.guess');
expect(text(where)).toBe('Likely, matched by class name: src/app/card.ts:8');
expect(where?.getAttribute('title')).toContain('no exact location');

openSourceButton(fixture).click();
await settle(fixture);
expect(bridge.openSource).toHaveBeenCalledWith(
'p1',
'c1',
expect.objectContaining({ file: 'src/app/card.ts', line: 8 }),
);
});

it('marks a single name match with another selector as likely', async () => {
const fixture = await render([scanned('src/app/card.ts', 'app-card-legacy')]);
expect(text(head(fixture).querySelector('.where.guess'))).toBe(
'Likely, matched by class name: src/app/card.ts:5',
);
});

it('lists every candidate when several classes may be it, and opens none of them', async () => {
const fixture = await render([
scanned('src/app/a/card.ts', 'a-card', 3),
scanned('src/app/b/card.ts', 'b-card', 9),
]);
const where = head(fixture).querySelector('.where.guess');
expect(text(where?.querySelector('.guess-text'))).toBe(
'Not certain 2 source files define Card:',
);
expect([...(where?.querySelectorAll('li') ?? [])].map(text)).toEqual([
'src/app/a/card.ts:3',
'src/app/b/card.ts:9',
]);

openSourceButton(fixture).click();
await settle(fixture);
expect(bridge.openSource).toHaveBeenCalledWith('p1', 'c1', null);
});
});
36 changes: 36 additions & 0 deletions app/src/__tests__/router-panels.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,42 @@ describe('RouteCurrent', () => {
expect(hidden).toEqual(['', ', level 2, child of (root)', ', level 3, child of /users']);
});

it('tells screen readers how each outlet is nested', async () => {
const fixture = mount(
RouteCurrent,
page({
outlets: [
{
outlet: 'primary',
activated: true,
component: 'Shell',
route: '/shell',
children: [
{
outlet: 'side',
activated: true,
component: 'Filters',
route: '/side',
children: [{ outlet: 'primary', activated: false }],
},
],
},
],
}),
offline,
);
await settle(fixture);
const rows = Array.from(el(fixture).querySelectorAll('.outlets li'));
const hidden = rows.map(
(row) => row.querySelector(':scope > .visually-hidden')?.textContent?.trim() ?? '',
);
expect(hidden).toEqual([
'',
'level 2, inside Shell in the primary outlet,',
'level 3, inside Filters in the side outlet,',
]);
});

it('reports an unreachable page on Abort instead of #undefined', async () => {
const fixture = mount(
RouteCurrent,
Expand Down
86 changes: 82 additions & 4 deletions app/src/pages/component-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,13 @@ function bare(name: string): string {
return name.replace(/^_(?=[A-Z])/, '');
}

/** True when two paths name the same file, one maybe longer or with `./` or backslashes. */
function sameSourceFile(a: string, b: string): boolean {
const norm = (path: string) => path.replace(/\\/g, '/').replace(/^\.\//, '');
const [x, y] = [norm(a), norm(b)];
return x === y || x.endsWith('/' + y) || y.endsWith('/' + x);
}

/** The ids above `id`, nearest first; stops at a repeated id so a bad map cannot loop. */
export function ancestors(parents: ReadonlyMap<string, string>, id: string): string[] {
const out: string[] = [];
Expand Down Expand Up @@ -473,10 +480,31 @@ function storedDirectiveHosts(): boolean {
<span class="badge">component</span>
<h2 id="ct-detail-title" class="mono">{{ sel.name }}</h2>
<span class="mono muted">&lt;{{ sel.tag }}&gt;</span>
@if (whereOf(sel); as where) {
@if (detail()?.source; as where) {
<p class="where mono">
<app-source-link [file]="where.file" [line]="where.line" />
</p>
} @else {
@let guesses = sourceCandidates(sel);
@if (guesses.length === 1) {
<p class="where mono guess" [title]="guessTitle">
<span class="likely">Likely</span
><span class="sr-only">, matched by class name: </span
><app-source-link [file]="guesses[0].file" [line]="guesses[0].line" />
</p>
} @else if (guesses.length > 1) {
<div class="where guess" [title]="guessTitle">
<p class="guess-text">
<span class="likely">Not certain</span>
{{ guesses.length }} source files define {{ bareName(sel.name) }}:
</p>
<ul class="guess-list mono">
@for (guess of guesses; track sourceKey(guess)) {
<li><app-source-link [file]="guess.file" [line]="guess.line" /></li>
}
</ul>
</div>
}
}
@if (devtoolsActions()) {
<div class="actions" role="group" aria-label="Chrome DevTools">
Expand Down Expand Up @@ -1397,6 +1425,28 @@ function storedDirectiveHosts(): boolean {
font-size: 12px;
overflow-wrap: anywhere;
}
.likely {
display: inline-block;
margin-right: 6px;
padding: 0 6px;
border: 1px solid;
border-radius: 99px;
@include m.tint(warn);
font-family: var(--font-sans);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
line-height: 16px;
text-transform: uppercase;
vertical-align: 1px;
}
.guess-text {
margin: 0;
}
.guess-list {
margin: 4px 0 0;
padding-left: 18px;
}
.badge {
padding: 2px 8px;
border-radius: 99px;
Expand Down Expand Up @@ -2210,8 +2260,15 @@ export class ComponentTree {
return this.formOwners().filter((form) => form.file === file);
}

/**
* The exact location the page gives, else the source scan's guess when only one class may be
* it. Several candidates give null, so Open source falls back to the class itself.
*/
whereOf(node: LiveNode): SourceLocation | null {
return this.detail()?.source ?? this.sourceFor(node);
const exact = this.detail()?.source;
if (exact) return exact;
const candidates = this.sourceCandidates(node);
return candidates.length === 1 ? candidates[0] : null;
}

async revealInElements(node: LiveNode) {
Expand Down Expand Up @@ -2248,11 +2305,32 @@ export class ComponentTree {
);
}

sourceFor(node: LiveNode): SourceComponent | null {
/** Why a location from the source scan is marked as a guess. */
protected readonly guessTitle =
'The page gave no exact location. This comes from the source scan, matched by class name.';

/**
* The source scan components that may define this instance, for when the page gives no exact
* location: the classes with its name, narrowed to those whose selector is its host tag when
* any is. More than one means the scan cannot tell which file it is.
*/
sourceCandidates(node: LiveNode): SourceComponent[] {
const matches = (this.sourceByClass().get(bare(node.name)) ?? []).filter(
(c) => c.kind === 'component',
);
return matches.find((c) => c.selector === node.tag) ?? matches[0] ?? null;
const bySelector = matches.filter((c) => c.selector === node.tag);
return bySelector.length ? bySelector : matches;
}

/**
* The source scan entry of this instance: the one in the file the page names, or the only
* candidate. Null when none matches or several may be it.
*/
sourceFor(node: LiveNode): SourceComponent | null {
const candidates = this.sourceCandidates(node);
const exact = this.detail()?.source;
if (exact) return candidates.find((c) => sameSourceFile(c.file, exact.file)) ?? null;
return candidates.length === 1 ? candidates[0] : null;
}

sourceKey(comp: SourceComponent) {
Expand Down
19 changes: 16 additions & 3 deletions app/src/pages/route-current.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,18 @@ interface RouteRow {
nesting?: string;
}

/** The outlet and the component it shows, as a screen reader names a parent outlet. */
function outletName(outlet: OutletInfo): string {
return outlet.component
? `${outlet.component} in the ${outlet.outlet} outlet`
: `the ${outlet.outlet} outlet`;
}

interface OutletRow {
outlet: OutletInfo;
depth: number;
/** What a screen reader hears for the nesting the indent shows, on nested outlets. */
nesting?: string;
}

@Component({
Expand Down Expand Up @@ -173,6 +182,9 @@ interface OutletRow {
@for (row of outletRows(); track $index) {
<li [style.padding-left.px]="10 + row.depth * 16">
<span class="tag">{{ row.outlet.outlet }}</span>
@if (row.nesting) {
<span class="visually-hidden">{{ row.nesting }}, </span>
}
@if (row.outlet.activated) {
<code>{{ row.outlet.component ?? '?' }}</code> for
<code>{{ row.outlet.route ?? '?' }}</code>
Expand Down Expand Up @@ -378,10 +390,11 @@ export class RouteCurrent {

readonly outletRows = computed(() => {
const rows: OutletRow[] = [];
const visit = (outlets: OutletInfo[], depth: number) => {
const visit = (outlets: OutletInfo[], depth: number, parent?: OutletInfo) => {
for (const outlet of outlets) {
rows.push({ outlet, depth });
if (outlet.children) visit(outlet.children, depth + 1);
const nesting = parent && `level ${depth + 1}, inside ${outletName(parent)}`;
rows.push({ outlet, depth, nesting });
if (outlet.children) visit(outlet.children, depth + 1, outlet);
}
};
visit(this.page().outlets ?? [], 0);
Expand Down
4 changes: 2 additions & 2 deletions apps/docs/src/content/inspectors/components.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ The tree shows up to 2000 component instances, and walks up to 256 levels of DOM

### Detail header

The header of the selected instance shows the class name, the host tag, and the source file and line. In a development build, the file and line come from the debug info Angular's compiler attaches to the component, so they point at the exact class. Without it, they come from the source scan, matched by class name. They are missing when neither has them. With a live devtools server, the file and line are a button that opens the file in your editor. See [Open a file in your editor](#open-a-file-in-your-editor).
The header of the selected instance shows the class name, the host tag, and the source file and line. In a development build, the file and line come from the debug info Angular's compiler attaches to the component, so they point at the exact class. Without it, they come from the source scan, matched by class name. When some of those classes have the host tag as their selector, only those are kept; otherwise every class with the name is kept. One match left is marked **Likely**. Several are listed under **Not certain**, and **Open source** then opens the compiled class. The file and line are missing when neither source has them. With a live devtools server, the file and line are a button that opens the file in your editor. See [Open a file in your editor](#open-a-file-in-your-editor).

In the [Chrome extension](../getting-started/chrome-extension.md), the header also has two buttons:

Expand Down Expand Up @@ -531,7 +531,7 @@ Instance ids change on every page load. Don't store them between sessions.
No page is connected, or the connected page is a production build. Open the app in a development build with the overlay loaded.
</ngmd-accordion-item>
<ngmd-accordion-item title="Why are the file and line missing?">
Production builds drop Angular's debug info. The detail header then matches the class name against the source scan, and classes outside the scanned folders, or from libraries, have no match.
Production builds drop Angular's debug info. The detail header then matches the class name against the source scan, keeping only classes whose selector is the host tag when there are any. One match is marked <strong>Likely</strong>; several are listed under <strong>Not certain</strong>. Classes outside the scanned folders, or from libraries, have no match, so no file shows.
</ngmd-accordion-item>
<ngmd-accordion-item title="Why does a component show +2?">
Two directives sit on its host element. Select it to see one block per directive.
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading