Skip to content

Commit b11b5ad

Browse files
committed
feat(react-devtools): drill into the saved React profile by component and commit
1 parent f25394b commit b11b5ad

8 files changed

Lines changed: 377 additions & 17 deletions

File tree

‎src/cli/react-profiler/react-profile-command.test.ts‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,20 @@ test('profile start, an interaction, and profile stop print a compact diagnosis
9696
'1. memo-defeated Row: memo bypassed on 36/36 updates; new onPress (function) on those updates from List -> wrap those props in useCallback/useMemo in List',
9797
);
9898
assert.ok(fs.existsSync(path.join(stateDir, 'react-profiles', 'qa.json')));
99+
100+
const report = await run('report', 'Row');
101+
assert.match(
102+
report.text,
103+
/^Row \[memo\] self 108ms avg 3\.0ms max 3\.0ms renders 36 12 inst\ncauses: props 36\nchanged props: onPress 36 \(function\)/,
104+
);
105+
assert.match(
106+
(await run('timeline', '--sort', 'duration', '--limit', '1')).text,
107+
/^Slowest commits \(1 of 3\):\n {2}#0 \+0\.0s 40ms 13 rendered <- List/,
108+
);
109+
assert.match(
110+
(await run('commit', '#1')).text,
111+
/^#1 \+0\.2s 40ms 13 rendered <- List\n {2}Row x12 self 36ms props/,
112+
);
99113
});
100114

101115
test('profile stop --json returns the findings and where the profile was saved', async () => {
@@ -176,6 +190,10 @@ test('runtime failures carry a typed reason and a hint', async () => {
176190
);
177191
});
178192

193+
test('drill-down views need a saved profile', async () => {
194+
await assert.rejects(harness().run('slow'), /No React profile saved for session qa/);
195+
});
196+
179197
test('explicit dev-server flags override the session binding', async () => {
180198
const { run, requested } = harness();
181199
await run('status', '--metro-port', '8082');
@@ -203,14 +221,26 @@ test('a remote bridge profiles through the public dev-server URL without its bun
203221
assert.deepEqual(requested, ['https://metro.example.test/json/list']);
204222
});
205223

224+
test('a corrupt saved profile asks for a new recording', async () => {
225+
const { run, stateDir } = harness();
226+
fs.mkdirSync(path.join(stateDir, 'react-profiles'), { recursive: true });
227+
const file = path.join(stateDir, 'react-profiles', 'qa.json');
228+
fs.writeFileSync(file, '{"analysis":');
229+
await assert.rejects(run('slow'), /unsupported format/);
230+
fs.writeFileSync(file, JSON.stringify({ analysis: { version: 1, components: {} } }));
231+
await assert.rejects(run('slow'), /unsupported format/);
232+
});
233+
206234
test('unknown profile commands and malformed options are invalid arguments', async () => {
207235
const { run } = harness();
208236
const cases: Array<[string[], RegExp]> = [
209237
[['export', 'out.json'], /Unknown react-devtools profile command: export/],
210-
[['stop', '--limit', '0'], /Invalid --limit: 0/],
211-
[['stop', '--limit', '10garbage'], /Invalid --limit: 10garbage/],
212-
[['stop', '--limit', '1.5'], /Invalid --limit: 1\.5/],
238+
[['slow', '--limit', '0'], /Invalid --limit: 0/],
239+
[['slow', '--limit', '10garbage'], /Invalid --limit: 10garbage/],
240+
[['slow', '--limit', '1.5'], /Invalid --limit: 1\.5/],
241+
[['timeline', '--sort', 'name'], /Invalid --sort: name/],
213242
[['stop', 'extra'], /Unexpected argument for react-devtools profile stop: extra/],
243+
[['report', 'Row', 'extra'], /Unexpected argument for react-devtools profile report: extra/],
214244
];
215245
for (const [args, message] of cases) {
216246
await assert.rejects(run(...args), (error: { code: string; message: string }) => {
@@ -220,3 +250,15 @@ test('unknown profile commands and malformed options are invalid arguments', asy
220250
});
221251
}
222252
});
253+
254+
test('commit selectors must be whole indexes', async () => {
255+
const { app, run } = harness();
256+
await run('start');
257+
recordRowRenders(app);
258+
await run('stop');
259+
await assert.rejects(
260+
run('commit', '#1junk'),
261+
(error: { code: string }) => error.code === 'INVALID_ARGS',
262+
);
263+
assert.match((await run('commit', '#1')).text, /^#1 /);
264+
});

‎src/cli/react-profiler/react-profile-command.ts‎

Lines changed: 122 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,35 @@ import {
2222
import { analyzeReactProfile, type ReactProfileAnalysis } from './react-profile-analysis.ts';
2323
import {
2424
selectPropKindRequests,
25+
type CommitProfile,
26+
type ComponentProfile,
2527
type PropKindsById,
2628
type RawReactProfile,
2729
} from './react-profile-renders.ts';
2830
import {
31+
componentsByRenders,
2932
DEFAULT_FINDING_LIMIT,
30-
formatProfileSummary,
33+
findComponent,
3134
formatSeconds,
35+
formatCommit,
36+
formatComponentReport,
37+
formatProfileSummary,
38+
formatRerenders,
39+
formatSlowComponents,
40+
formatTimeline,
41+
timelineCommits,
3242
} from './react-profile-format.ts';
3343

34-
const REACT_PROFILE_SUBCOMMANDS = ['start', 'stop', 'status'] as const;
44+
const REACT_PROFILE_SUBCOMMANDS = [
45+
'start',
46+
'stop',
47+
'status',
48+
'slow',
49+
'rerenders',
50+
'report',
51+
'timeline',
52+
'commit',
53+
] as const;
3554

3655
type ReactProfileSubcommand = (typeof REACT_PROFILE_SUBCOMMANDS)[number];
3756

@@ -43,15 +62,17 @@ export type ReactProfileCommandOptions = {
4362

4463
type ProfileArgs = {
4564
subcommand: ReactProfileSubcommand;
65+
target?: string;
4666
limit?: number;
4767
app?: string;
4868
metroDevice?: string;
4969
metroHost?: string;
5070
metroPort?: string;
5171
bundleUrl?: string;
72+
sort?: 'timeline' | 'duration';
5273
};
5374

54-
/** Analysis plus the runtime it came from, as `profile stop` saves it for the session. */
75+
/** Analysis plus the runtime it came from, as `profile stop` saves it for the drill-down views. */
5576
type SavedReactProfile = {
5677
savedAt: string;
5778
appId?: string;
@@ -64,6 +85,7 @@ type StartResult = { ok: true; attach: string } | RuntimeFailure;
6485
type StopResult = ({ ok: true } & RawReactProfile) | RuntimeFailure;
6586
type StatusResult = { profiling: boolean; elapsedMs: number | null };
6687

88+
const SUBCOMMANDS_WITH_TARGET = new Set<ReactProfileSubcommand>(['report', 'commit']);
6789
const POSITIVE_INTEGER = /^[1-9]\d*$/;
6890

6991
function isReactProfileSubcommand(value: string | undefined): value is ReactProfileSubcommand {
@@ -77,6 +99,7 @@ const PROFILE_OPTIONS = {
7799
'metro-host': { type: 'string' },
78100
'metro-port': { type: 'string' },
79101
'bundle-url': { type: 'string' },
102+
sort: { type: 'string' },
80103
} as const;
81104

82105
function parseProfileOptions(args: string[]) {
@@ -97,24 +120,30 @@ function parseProfileArgs(args: string[]): ProfileArgs {
97120
);
98121
}
99122
const { values, positionals } = parseProfileOptions(rest);
100-
if (positionals.length > 0) {
123+
const expected = SUBCOMMANDS_WITH_TARGET.has(subcommand) ? 1 : 0;
124+
if (positionals.length > expected) {
101125
throw new AppError(
102126
'INVALID_ARGS',
103-
`Unexpected argument for react-devtools profile ${subcommand}: ${positionals[0]}.`,
127+
`Unexpected argument for react-devtools profile ${subcommand}: ${positionals[expected]}.`,
104128
);
105129
}
106130
if (values.limit !== undefined && !POSITIVE_INTEGER.test(values.limit)) {
107131
throw new AppError('INVALID_ARGS', `Invalid --limit: ${values.limit}. Use a positive integer.`);
108132
}
109133
const limit = values.limit === undefined ? undefined : Number(values.limit);
134+
if (values.sort !== undefined && values.sort !== 'timeline' && values.sort !== 'duration') {
135+
throw new AppError('INVALID_ARGS', `Invalid --sort: ${values.sort}. Use timeline or duration.`);
136+
}
110137
return {
111138
subcommand,
139+
target: positionals[0],
112140
limit,
113141
app: values.app,
114142
metroDevice: values['metro-device'],
115143
metroHost: values['metro-host'],
116144
metroPort: values['metro-port'],
117145
bundleUrl: values['bundle-url'],
146+
sort: values.sort as ProfileArgs['sort'],
118147
};
119148
}
120149

@@ -224,6 +253,39 @@ function writeSavedProfile(
224253
return filePath;
225254
}
226255

256+
function isSavedProfile(value: SavedReactProfile | undefined): value is SavedReactProfile {
257+
const analysis = value?.analysis;
258+
return (
259+
analysis?.version === 1 &&
260+
Array.isArray(analysis.components) &&
261+
Array.isArray(analysis.commits) &&
262+
Array.isArray(analysis.findings)
263+
);
264+
}
265+
266+
function readSavedProfile(options: ReactProfileCommandOptions): SavedReactProfile {
267+
let raw: string;
268+
try {
269+
raw = fs.readFileSync(savedProfilePath(options), 'utf8');
270+
} catch {
271+
throw new AppError('COMMAND_FAILED', `No React profile saved for session ${options.session}.`, {
272+
hint: 'Run react-devtools profile start, perform the interaction, then react-devtools profile stop.',
273+
});
274+
}
275+
let saved: SavedReactProfile | undefined;
276+
try {
277+
saved = JSON.parse(raw) as SavedReactProfile;
278+
} catch {
279+
saved = undefined;
280+
}
281+
if (!isSavedProfile(saved)) {
282+
throw new AppError('COMMAND_FAILED', 'The saved React profile has an unsupported format.', {
283+
hint: 'Record a new profile with react-devtools profile start and stop.',
284+
});
285+
}
286+
return saved;
287+
}
288+
227289
const elapsed = (elapsedMs: number) => formatSeconds(Math.max(0, elapsedMs));
228290

229291
async function startProfile(
@@ -302,6 +364,32 @@ type SubcommandHandler = (
302364
emit: Emit,
303365
) => Promise<void>;
304366

367+
function requireComponent(
368+
analysis: ReactProfileAnalysis,
369+
name: string | undefined,
370+
): ComponentProfile {
371+
if (!name)
372+
throw new AppError('INVALID_ARGS', 'react-devtools profile report requires a component name.');
373+
const component = findComponent(analysis, name);
374+
if (!component) {
375+
throw new AppError('COMMAND_FAILED', `No renders of ${name} in the saved profile.`, {
376+
hint: 'Use a name from react-devtools profile slow or profile rerenders.',
377+
});
378+
}
379+
return component;
380+
}
381+
382+
function requireCommit(analysis: ReactProfileAnalysis, target: string | undefined): CommitProfile {
383+
const digits = (target ?? '').replace(/^#/, '');
384+
const commit = /^\d+$/.test(digits) ? analysis.commits[Number(digits)] : undefined;
385+
if (!commit) {
386+
throw new AppError('INVALID_ARGS', `No commit ${target ?? '(none)'} in the saved profile.`, {
387+
hint: `Use a commit index from 0 to ${Math.max(analysis.commits.length - 1, 0)}.`,
388+
});
389+
}
390+
return commit;
391+
}
392+
305393
const SUBCOMMAND_HANDLERS: Record<ReactProfileSubcommand, SubcommandHandler> = {
306394
start: async (args, options, emit) => {
307395
const started = await startProfile(args, options);
@@ -328,6 +416,35 @@ const SUBCOMMAND_HANDLERS: Record<ReactProfileSubcommand, SubcommandHandler> = {
328416
savedTo: savedProfilePath(options),
329417
});
330418
},
419+
slow: async (args, options, emit) => {
420+
const { analysis } = readSavedProfile(options);
421+
const limit = args.limit ?? 10;
422+
emit(formatSlowComponents(analysis, limit), analysis.components.slice(0, limit));
423+
},
424+
rerenders: async (args, options, emit) => {
425+
const { analysis } = readSavedProfile(options);
426+
const limit = args.limit ?? 10;
427+
emit(formatRerenders(analysis, limit), componentsByRenders(analysis).slice(0, limit));
428+
},
429+
report: async (args, options, emit) => {
430+
const { analysis } = readSavedProfile(options);
431+
const component = requireComponent(analysis, args.target);
432+
emit(formatComponentReport(analysis, component), component);
433+
},
434+
timeline: async (args, options, emit) => {
435+
const { analysis } = readSavedProfile(options);
436+
const limit = args.limit ?? 20;
437+
const byDuration = args.sort === 'duration';
438+
emit(
439+
formatTimeline(analysis, limit, byDuration),
440+
timelineCommits(analysis, byDuration).slice(0, limit),
441+
);
442+
},
443+
commit: async (args, options, emit) => {
444+
const { analysis } = readSavedProfile(options);
445+
const commit = requireCommit(analysis, args.target);
446+
emit(formatCommit(commit, args.limit ?? 10), commit);
447+
},
331448
};
332449

333450
export async function runReactProfileCommand(

‎src/cli/react-profiler/react-profile-format.test.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@ import { test } from 'vitest';
22
import assert from 'node:assert/strict';
33
import type { Finding, ReactProfileAnalysis } from './react-profile-analysis.ts';
44
import type { ComponentProfile } from './react-profile-renders.ts';
5-
import { formatProfileSummary } from './react-profile-format.ts';
5+
import {
6+
findComponent,
7+
formatProfileSummary,
8+
formatRerenders,
9+
formatSlowComponents,
10+
formatTimeline,
11+
} from './react-profile-format.ts';
612

713
function component(name: string, overrides: Partial<ComponentProfile> = {}): ComponentProfile {
814
return {
@@ -69,19 +75,20 @@ function analysis(overrides: Partial<ReactProfileAnalysis> = {}): ReactProfileAn
6975
};
7076
}
7177

72-
test('the summary is a headline and one line per finding', () => {
78+
test('the summary is a headline, one line per finding, and the drill-down commands', () => {
7379
assert.equal(
7480
formatProfileSummary(analysis()),
7581
[
7682
'React profile 3.2s: 4 commits, 96ms rendering, 2 over 16ms (worst #2 42ms)',
7783
'1. slow-render C1: slow -> memoize',
84+
'More: profile slow | profile rerenders | profile report <Component> | profile timeline | profile commit <N>',
7885
].join('\n'),
7986
);
8087
});
8188

8289
test('the summary caps findings and says how to see the rest', () => {
8390
const text = formatProfileSummary(analysis({ findings: [1, 2, 3, 4].map(finding) }), 2);
84-
assert.match(text, /\n2\. slow-render C2: slow -> memoize\n\+2 smaller findings \(--limit 4\)$/);
91+
assert.match(text, /\n2\. slow-render C2: slow -> memoize\n\+2 smaller findings \(--limit 4\)\n/);
8592
});
8693

8794
test('the summary reports clean profiles and empty recordings in one line', () => {
@@ -101,3 +108,27 @@ test('lookup naming warns that unmounted components may be unnamed', () => {
101108
/\nNote: component names came from mounted elements/,
102109
);
103110
});
111+
112+
test('slow and rerender tables rank by self time and render count', () => {
113+
assert.match(
114+
formatSlowComponents(analysis(), 1),
115+
/^Components by self time:\n {2}Chart \[function\] self 40ms avg 10ms max 12ms renders 4\n {2}\+1 more \(--limit 2\)$/,
116+
);
117+
assert.match(
118+
formatRerenders(analysis(), 1),
119+
/^Components by render count:\n {2}Row \[function\] 9 renders 3 inst: props 3, mount 1; changed props onPress 3\n {2}\+1 more \(--limit 2\)$/,
120+
);
121+
});
122+
123+
test('the timeline lists commits with their trigger and mounts', () => {
124+
assert.equal(
125+
formatTimeline(analysis(), 5, false),
126+
'Commits:\n #0 +0.0s 10ms 3 rendered <- List\n #1 +0.9s 42ms 30 rendered (30 mounted)',
127+
);
128+
assert.match(formatTimeline(analysis(), 1, true), /^Slowest commits \(1 of 2\):\n {2}#1/);
129+
});
130+
131+
test('component lookup falls back to a case-insensitive match', () => {
132+
assert.equal(findComponent(analysis(), 'chart')?.name, 'Chart');
133+
assert.equal(findComponent(analysis(), 'Missing'), undefined);
134+
});

0 commit comments

Comments
 (0)