mirror of
https://github.com/facebook/react.git
synced 2026-11-18 20:15:56 +00:00
Added initial Suspense cache and loaded commit metadata
This commit is contained in:
1 parent
e7e62acbf9
commit
b8a52078c6
13 files changed
+624
-80
No files matched your search
+4
-4
@@ -14,7 +14,7 @@ The old DevTools also rendered the entire application tree in the form of a larg
|
||||
|
||||
Every React commit that changes the tree in a way DevTools cares about results in an "_operations_" message being sent across the bridge. These messages are lightweight patches that describe the changes that were made. (We don't resend the full tree structure like in legacy DevTools.)
|
||||
|
||||
The payload for each message is a typed array. The first entry is a number identifying which renderer the update belongs to (for multi-root support). The rest of the array depends on the operations being made to the tree.
|
||||
The payload for each message is a typed array. The first two entries are numbers that identify which renderer and root the update belongs to (for multi-root support). The rest of the array depends on the operations being made to the tree.
|
||||
|
||||
We only send the following bits of information: element type, id, parent id, owner id, name, and key. Additional information (e.g. props, state) requires a separate "_inspectElement_" message.
|
||||
|
||||
@@ -188,7 +188,7 @@ This information is kept on the backend until requested by the frontend (as desc
|
||||
|
||||
The profiling tab shows information for the currently-selected React root. When profiling completes (or when a new root is selected) the frontend first checks to see if there is any profiling data for the selected root. (Has it cached any "_operations_"?)
|
||||
|
||||
If so, then it sends a "_profileSummary_" message with an id that identifies the root. The backend then returns the following information:
|
||||
If so, then it sends a "_getProfilingSummary_" message with an id that identifies the root. The backend then returns a "_profilingSummary_" message with the following information:
|
||||
|
||||
* root id (to match request and response)
|
||||
* number of interactions that were traced for this root
|
||||
@@ -216,7 +216,7 @@ Here is an example profile summary:
|
||||
],
|
||||
|
||||
// Tuples of fiber id and initial tree base duration
|
||||
treeBaseDuration: [
|
||||
initialTreeBaseDurations: [
|
||||
1, // fiber id
|
||||
11, // tree base duration when profiling started
|
||||
|
||||
@@ -335,4 +335,4 @@ Here is an example of a profiling session consisting of two interactions:
|
||||
}
|
||||
```
|
||||
|
||||
The backend does not need to resend the timestamp for each of the commits because that was already sent as part of the "_profileSummary_" message.
|
||||
The backend does not need to resend the timestamp for each of the commits because that was already sent as part of the "_profilingSummary_" message.
|
||||
+20
-1
@@ -47,6 +47,7 @@ export default class Agent extends EventEmitter {
|
||||
this._bridge = bridge;
|
||||
|
||||
bridge.addListener('getProfilingStatus', this.getProfilingStatus);
|
||||
bridge.addListener('getProfilingSummary', this.getProfilingSummary);
|
||||
bridge.addListener('highlightElementInDOM', this.highlightElementInDOM);
|
||||
bridge.addListener('inspectElement', this.inspectElement);
|
||||
bridge.addListener('overrideContext', this.overrideContext);
|
||||
@@ -79,6 +80,24 @@ export default class Agent extends EventEmitter {
|
||||
this._bridge.send('profilingStatus', this._isProfiling);
|
||||
};
|
||||
|
||||
getProfilingSummary = ({
|
||||
rendererID,
|
||||
rootID,
|
||||
}: {
|
||||
rendererID: number,
|
||||
rootID: number,
|
||||
}) => {
|
||||
const renderer = this._rendererInterfaces[rendererID];
|
||||
if (renderer == null) {
|
||||
console.warn(`Invalid renderer id "${rendererID}"`);
|
||||
} else {
|
||||
this._bridge.send(
|
||||
'profilingSummary',
|
||||
renderer.getProfilingSummary(rootID)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
highlightElementInDOM = ({
|
||||
displayName,
|
||||
id,
|
||||
@@ -216,7 +235,7 @@ export default class Agent extends EventEmitter {
|
||||
const renderer = ((this._rendererInterfaces[
|
||||
(rendererID: any)
|
||||
]: any): RendererInterface);
|
||||
renderer.startProfiling();
|
||||
renderer.stopProfiling();
|
||||
}
|
||||
this._bridge.send('profilingStatus', this._isProfiling);
|
||||
};
|
||||
|
||||
+89
-22
@@ -26,9 +26,10 @@ import { inspectHooksOfFiber } from './ReactDebugHooks';
|
||||
import type {
|
||||
DevToolsHook,
|
||||
Fiber,
|
||||
Interaction,
|
||||
ReactRenderer,
|
||||
FiberData,
|
||||
Interaction,
|
||||
ProfilingSummary,
|
||||
ReactRenderer,
|
||||
RendererInterface,
|
||||
} from './types';
|
||||
import type { InspectedElement } from 'src/devtools/views/elements/types';
|
||||
@@ -466,6 +467,13 @@ export function attach(
|
||||
// and use a slow path to find each of the current Fibers.
|
||||
const idToTreeBaseDurationMap: Map<number, number> = new Map();
|
||||
|
||||
// When profiling is supported, we store the latest tree base durations for each Fiber.
|
||||
// This map enables us to filter these times by root when sending them to the frontend.
|
||||
const idToRootMap: Map<number, number> = new Map();
|
||||
|
||||
// When a mount or update is in progress, this value tracks the root that is being operated on.
|
||||
let currentRootID: number = -1;
|
||||
|
||||
function getFiberID(primaryFiber: Fiber): number {
|
||||
if (!fiberToIDMap.has(primaryFiber)) {
|
||||
const id = getUID();
|
||||
@@ -543,8 +551,9 @@ export function attach(
|
||||
// Identify which renderer this update is coming from.
|
||||
// This enables roots to be mapped to renderers,
|
||||
// Which in turn enables fiber props, states, and hooks to be inspected.
|
||||
const idArray = new Uint32Array(1);
|
||||
const idArray = new Uint32Array(2);
|
||||
idArray[0] = rendererID;
|
||||
idArray[1] = getFiberID(getPrimaryFiber(root.current));
|
||||
addOperation(idArray, true);
|
||||
|
||||
// Let the frontend know about tree operations.
|
||||
@@ -560,6 +569,7 @@ export function attach(
|
||||
|
||||
const isProfilingSupported = fiber.hasOwnProperty('treeBaseDuration');
|
||||
if (isProfilingSupported) {
|
||||
idToRootMap.set(id, currentRootID);
|
||||
idToTreeBaseDurationMap.set(id, fiber.treeBaseDuration);
|
||||
}
|
||||
|
||||
@@ -636,8 +646,13 @@ export function attach(
|
||||
}
|
||||
fiberToIDMap.delete(primaryFiber);
|
||||
idToFiberMap.delete(id);
|
||||
idToTreeBaseDurationMap.delete(primaryFiber);
|
||||
primaryFibers.delete(primaryFiber);
|
||||
|
||||
const isProfilingSupported = fiber.hasOwnProperty('treeBaseDuration');
|
||||
if (isProfilingSupported) {
|
||||
idToRootMap.delete(id);
|
||||
idToTreeBaseDurationMap.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
function mountFiber(fiber: Fiber, parentFiber: Fiber | null) {
|
||||
@@ -672,13 +687,16 @@ export function attach(
|
||||
|
||||
if (fiber.actualDuration > 0) {
|
||||
// If profiling is active, store durations for elements that were rendered during the commit.
|
||||
((currentCommitProfilingMetadata: any): CommitProfilingData).committedFibers.push(
|
||||
{
|
||||
id,
|
||||
actualDuration: fiber.actualDuration,
|
||||
selfDuration: fiber.selfDuration,
|
||||
treeBaseDuration: fiber.treeBaseDuration,
|
||||
}
|
||||
const metadata = ((currentCommitProfilingMetadata: any): CommitProfilingData);
|
||||
metadata.committedFibers.push({
|
||||
id,
|
||||
actualDuration: fiber.actualDuration,
|
||||
selfDuration: fiber.selfDuration,
|
||||
treeBaseDuration: fiber.treeBaseDuration,
|
||||
});
|
||||
metadata.maxActualDuration = Math.max(
|
||||
metadata.maxActualDuration,
|
||||
fiber.actualDuration
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -819,8 +837,10 @@ export function attach(
|
||||
function walkTree() {
|
||||
// Hydrate all the roots for the first time.
|
||||
hook.getFiberRoots(rendererID).forEach(root => {
|
||||
currentRootID = getFiberID(getPrimaryFiber(root.current));
|
||||
mountFiber(root.current, null);
|
||||
flushPendingEvents(root);
|
||||
currentRootID = -1;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -835,6 +855,8 @@ export function attach(
|
||||
const current = root.current;
|
||||
const alternate = current.alternate;
|
||||
|
||||
currentRootID = getFiberID(getPrimaryFiber(current));
|
||||
|
||||
if (isProfiling) {
|
||||
// If profiling is active, store commit time and duration, and the current interactions.
|
||||
// The frontend may request this information after profiling has stopped.
|
||||
@@ -847,6 +869,7 @@ export function attach(
|
||||
timestamp: timestamp - profilingStartTime,
|
||||
})
|
||||
),
|
||||
maxActualDuration: 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -873,13 +896,25 @@ export function attach(
|
||||
}
|
||||
|
||||
if (isProfiling) {
|
||||
((commitProfilingMetadata: any): Array<CommitProfilingData>).push(
|
||||
((currentCommitProfilingMetadata: any): CommitProfilingData)
|
||||
const commitProfilingMetadata = ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).get(
|
||||
currentRootID
|
||||
);
|
||||
if (commitProfilingMetadata != null) {
|
||||
commitProfilingMetadata.push(
|
||||
((currentCommitProfilingMetadata: any): CommitProfilingData)
|
||||
);
|
||||
} else {
|
||||
((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).set(
|
||||
currentRootID,
|
||||
[((currentCommitProfilingMetadata: any): CommitProfilingData)]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// We're done here.
|
||||
flushPendingEvents(root);
|
||||
|
||||
currentRootID = -1;
|
||||
}
|
||||
|
||||
// The naming is confusing.
|
||||
@@ -1333,24 +1368,55 @@ export function attach(
|
||||
committedFibers: Array<CommittedFiber>,
|
||||
commitTime: number,
|
||||
interactions: Array<Interaction>,
|
||||
maxActualDuration: number,
|
||||
|};
|
||||
|
||||
let commitProfilingMetadata: Array<CommitProfilingData> | null = null;
|
||||
type CommitProfilingMetadataMap = Map<number, Array<CommitProfilingData>>;
|
||||
|
||||
let currentCommitProfilingMetadata: CommitProfilingData | null = null;
|
||||
let initialTreeBaseDurations: Array<number> | null = null;
|
||||
let initialTreeBaseDurationsMap: Map<number, number> | null = null;
|
||||
let isProfiling: boolean = false;
|
||||
let profilingStartTime: number = 0;
|
||||
let rootToCommitProfilingMetadataMap: CommitProfilingMetadataMap | null = null;
|
||||
|
||||
function getProfilingSummary(rootID: number): ProfilingSummary {
|
||||
const interactions = new Set();
|
||||
const commits = [];
|
||||
|
||||
const commitProfilingMetadata = ((rootToCommitProfilingMetadataMap: any): CommitProfilingMetadataMap).get(
|
||||
rootID
|
||||
);
|
||||
if (commitProfilingMetadata != null) {
|
||||
commitProfilingMetadata.forEach(metadata => {
|
||||
commits.push(metadata.commitTime, metadata.maxActualDuration);
|
||||
metadata.interactions.forEach(({ name, timestamp }) => {
|
||||
interactions.add(`${timestamp}:${name}`);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const initialTreeBaseDurations = [];
|
||||
((initialTreeBaseDurationsMap: any): Map<number, number>).forEach(
|
||||
(treeBaseDuration, id) => {
|
||||
if (idToRootMap.get(id) === rootID) {
|
||||
initialTreeBaseDurations.push(id, treeBaseDuration);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
commits,
|
||||
initialTreeBaseDurations,
|
||||
interactionCount: interactions.size,
|
||||
rootID,
|
||||
};
|
||||
}
|
||||
|
||||
function startProfiling() {
|
||||
commitProfilingMetadata = [];
|
||||
initialTreeBaseDurations = [];
|
||||
initialTreeBaseDurationsMap = new Map(idToTreeBaseDurationMap);
|
||||
isProfiling = true;
|
||||
profilingStartTime = performance.now();
|
||||
|
||||
// Save initial treeBaseDurations; we'll need to send them later.
|
||||
idToTreeBaseDurationMap.forEach((treeBaseDuration: number, id: number) => {
|
||||
initialTreeBaseDurations = [id, treeBaseDuration];
|
||||
});
|
||||
rootToCommitProfilingMetadataMap = new Map();
|
||||
}
|
||||
|
||||
function stopProfiling() {
|
||||
@@ -1361,6 +1427,7 @@ export function attach(
|
||||
cleanup,
|
||||
getFiberIDFromNative,
|
||||
getNativeFromReactElement,
|
||||
getProfilingSummary,
|
||||
handleCommitFiberRoot,
|
||||
handleCommitFiberUnmount,
|
||||
inspectElement,
|
||||
|
||||
@@ -54,6 +54,13 @@ export type ReactRenderer = {
|
||||
currentDispatcherRef?: {| current: null | Dispatcher |},
|
||||
};
|
||||
|
||||
export type ProfilingSummary = {|
|
||||
commits: Array<number>,
|
||||
initialTreeBaseDurations: Array<number>,
|
||||
interactionCount: number,
|
||||
rootID: number,
|
||||
|};
|
||||
|
||||
export type RendererInterface = {
|
||||
cleanup: () => void,
|
||||
getNativeFromReactElement?: ?(component: Fiber) => ?NativeType,
|
||||
@@ -61,6 +68,7 @@ export type RendererInterface = {
|
||||
component: NativeType,
|
||||
findNearestUnfilteredAncestor?: boolean
|
||||
) => number | null,
|
||||
getProfilingSummary: (rootID: number) => ProfilingSummary,
|
||||
handleCommitFiberRoot: (fiber: Object) => void,
|
||||
handleCommitFiberUnmount: (fiber: Object) => void,
|
||||
inspectElement: (id: number) => InspectedElement | null,
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// @flow
|
||||
|
||||
import { createResource, invalidateResources } from './cache';
|
||||
import Store from './store';
|
||||
|
||||
import type { Resource } from './cache';
|
||||
import type { Bridge } from '../types';
|
||||
import type { ProfilingSummary as ProfilingSummaryBackend } from 'src/backend/types';
|
||||
import type { ProfilingSummary as ProfilingSummaryFrontend } from 'src/devtools/views/Profiler/types';
|
||||
|
||||
type AAA = {|
|
||||
rootID: number,
|
||||
rendererID: number,
|
||||
|};
|
||||
|
||||
export default class ProfilingCache {
|
||||
_pendingProfileSummaryMap: Map<
|
||||
number,
|
||||
(profilingSummary: ProfilingSummaryFrontend) => void
|
||||
> = new Map();
|
||||
|
||||
ProfilingSummary: Resource<AAA, ProfilingSummaryFrontend>;
|
||||
|
||||
// TODO (profiling) renderer + root
|
||||
|
||||
constructor(bridge: Bridge, store: Store) {
|
||||
this.ProfilingSummary = createResource(
|
||||
({ rendererID, rootID }: AAA) => {
|
||||
return new Promise(resolve => {
|
||||
if (!store._profilingOperations.has(rootID)) {
|
||||
// If no profiling data was recorded for this root, skip the round trip.
|
||||
resolve({
|
||||
commits: [],
|
||||
initialTreeBaseDurations: new Map(),
|
||||
interactionCount: 0,
|
||||
});
|
||||
} else {
|
||||
this._pendingProfileSummaryMap.set(rootID, resolve);
|
||||
bridge.send('getProfilingSummary', { rendererID, rootID });
|
||||
}
|
||||
});
|
||||
},
|
||||
({ rendererID, rootID }: AAA) => rootID
|
||||
);
|
||||
|
||||
bridge.addListener('profilingSummary', this.onProfileSummary);
|
||||
}
|
||||
|
||||
invalidate() {
|
||||
invalidateResources();
|
||||
this._pendingProfileSummaryMap = new Map();
|
||||
}
|
||||
|
||||
onProfileSummary = ({
|
||||
commits,
|
||||
initialTreeBaseDurations,
|
||||
interactionCount,
|
||||
rootID,
|
||||
}: ProfilingSummaryBackend) => {
|
||||
const resolve = this._pendingProfileSummaryMap.get(rootID);
|
||||
if (resolve != null) {
|
||||
const initialTreeBaseDurationsMap = new Map();
|
||||
for (let i = 0; i < initialTreeBaseDurations.length; i++) {
|
||||
initialTreeBaseDurationsMap.set(
|
||||
initialTreeBaseDurations[i],
|
||||
initialTreeBaseDurations[i + 1]
|
||||
);
|
||||
}
|
||||
|
||||
resolve({
|
||||
commits,
|
||||
initialTreeBaseDurations: initialTreeBaseDurationsMap,
|
||||
interactionCount,
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// @flow
|
||||
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
// Cache implementation was forked from the React repo:
|
||||
// https://github.com/facebook/react/blob/master/packages/react-cache/src/ReactCache.js
|
||||
//
|
||||
// This cache is simpler than react-cache in that:
|
||||
// 1. Individual items don't need to be invalidated.
|
||||
// Profiling data is invalidated as a whole.
|
||||
// 2. We didn't need the added overhead of an LRU cache.
|
||||
// The size of this cache is bounded by how many renders were profiled,
|
||||
// and it will be fully reset between profiling sessions.
|
||||
|
||||
type Thenable<T> = {
|
||||
then(resolve: (T) => mixed, reject: (mixed) => mixed): mixed,
|
||||
};
|
||||
|
||||
type Suspender = {
|
||||
then(resolve: () => mixed, reject: () => mixed): mixed,
|
||||
};
|
||||
|
||||
type PendingResult = {|
|
||||
status: 0,
|
||||
value: Suspender,
|
||||
|};
|
||||
|
||||
type ResolvedResult<V> = {|
|
||||
status: 1,
|
||||
value: V,
|
||||
|};
|
||||
|
||||
type RejectedResult = {|
|
||||
status: 2,
|
||||
value: mixed,
|
||||
|};
|
||||
|
||||
type Result<V> = PendingResult | ResolvedResult<V> | RejectedResult;
|
||||
|
||||
export type Resource<I, V> = {
|
||||
read(I): V,
|
||||
preload(I): void,
|
||||
};
|
||||
|
||||
const Pending = 0;
|
||||
const Resolved = 1;
|
||||
const Rejected = 2;
|
||||
|
||||
function identityHashFn(input) {
|
||||
return input;
|
||||
}
|
||||
|
||||
const CacheContext = createContext(null);
|
||||
|
||||
const entries: Map<Resource<any, any>, Map<any, any>> = new Map();
|
||||
|
||||
function accessResult<I, K, V>(
|
||||
resource: any,
|
||||
fetch: I => Thenable<V>,
|
||||
input: I,
|
||||
key: K
|
||||
): Result<V> {
|
||||
let entriesForResource = entries.get(resource);
|
||||
if (entriesForResource === undefined) {
|
||||
entriesForResource = new Map();
|
||||
entries.set(resource, entriesForResource);
|
||||
}
|
||||
let entry = entriesForResource.get(key);
|
||||
if (entry === undefined) {
|
||||
const thenable = fetch(input);
|
||||
thenable.then(
|
||||
value => {
|
||||
if (newResult.status === Pending) {
|
||||
const resolvedResult: ResolvedResult<V> = (newResult: any);
|
||||
resolvedResult.status = Resolved;
|
||||
resolvedResult.value = value;
|
||||
}
|
||||
},
|
||||
error => {
|
||||
if (newResult.status === Pending) {
|
||||
const rejectedResult: RejectedResult = (newResult: any);
|
||||
rejectedResult.status = Rejected;
|
||||
rejectedResult.value = error;
|
||||
}
|
||||
}
|
||||
);
|
||||
const newResult: PendingResult = {
|
||||
status: Pending,
|
||||
value: thenable,
|
||||
};
|
||||
entriesForResource.set(key, newResult);
|
||||
return newResult;
|
||||
} else {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
export function createResource<I, K: string | number, V>(
|
||||
fetch: I => Thenable<V>,
|
||||
maybeHashInput?: I => K
|
||||
): Resource<I, V> {
|
||||
const hashInput: I => K =
|
||||
maybeHashInput !== undefined ? maybeHashInput : (identityHashFn: any);
|
||||
|
||||
const resource = {
|
||||
read(input: I): V {
|
||||
// Prevent access outside of render.
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
useContext(CacheContext);
|
||||
|
||||
const key = hashInput(input);
|
||||
const result: Result<V> = accessResult(resource, fetch, input, key);
|
||||
switch (result.status) {
|
||||
case Pending: {
|
||||
const suspender = result.value;
|
||||
throw suspender;
|
||||
}
|
||||
case Resolved: {
|
||||
const value = result.value;
|
||||
return value;
|
||||
}
|
||||
case Rejected: {
|
||||
const error = result.value;
|
||||
throw error;
|
||||
}
|
||||
default:
|
||||
// Should be unreachable
|
||||
return (undefined: any);
|
||||
}
|
||||
},
|
||||
|
||||
preload(input: I): void {
|
||||
// Prevent access outside of render.
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
useContext(CacheContext);
|
||||
|
||||
const key = hashInput(input);
|
||||
accessResult(resource, fetch, input, key);
|
||||
},
|
||||
};
|
||||
return resource;
|
||||
}
|
||||
|
||||
export function invalidateResources(): void {
|
||||
entries.clear();
|
||||
}
|
||||
+55
-7
@@ -9,6 +9,7 @@ import {
|
||||
import { ElementTypeRoot } from './types';
|
||||
import { utfDecodeString } from '../utils';
|
||||
import { __DEBUG__ } from '../constants';
|
||||
import ProfilingCache from './ProfilingCache';
|
||||
|
||||
import type { ElementType } from './types';
|
||||
import type { Element } from './views/elements/types';
|
||||
@@ -47,6 +48,7 @@ export default class Store extends EventEmitter {
|
||||
// Elements are mutable (for now) to avoid excessive cloning during tree updates.
|
||||
_idToElement: Map<number, Element> = new Map();
|
||||
|
||||
// The backend is currently profiling.
|
||||
// When profiling is in progress, operations are stored so that we can later reconstruct past commit trees.
|
||||
_isProfiling: boolean = false;
|
||||
|
||||
@@ -54,7 +56,10 @@ export default class Store extends EventEmitter {
|
||||
// Used for windowing purposes.
|
||||
_numElements: number = 0;
|
||||
|
||||
// List of tree mutation that occur during profiling.
|
||||
// Suspense cache for reading profilign data.
|
||||
_profilingCache: ProfilingCache;
|
||||
|
||||
// Map of root (id) to a list of tree mutation that occur during profiling.
|
||||
// Once profiling is finished, these mutations can be used, along with the initial tree snapshots,
|
||||
// to reconstruct the state of each root for each commit.
|
||||
_profilingOperations: Map<number, Array<Uint32Array>> = new Map();
|
||||
@@ -93,12 +98,27 @@ export default class Store extends EventEmitter {
|
||||
// It's possible that profiling has already started (e.g. "reload and start profiling")
|
||||
// so the frontend needs to ask the backend for its status after mounting.
|
||||
bridge.send('getProfilingStatus');
|
||||
|
||||
this._profilingCache = new ProfilingCache(bridge, this);
|
||||
}
|
||||
|
||||
// Profiling data has been recorded for at least one root.
|
||||
get hasProfilingData(): boolean {
|
||||
return this._profilingOperations.size > 0;
|
||||
}
|
||||
|
||||
get isProfiling(): boolean {
|
||||
return this._isProfiling;
|
||||
}
|
||||
|
||||
get numElements(): number {
|
||||
return this._numElements;
|
||||
}
|
||||
|
||||
get profilingCache(): ProfilingCache {
|
||||
return this._profilingCache;
|
||||
}
|
||||
|
||||
get revision(): number {
|
||||
return this._revision;
|
||||
}
|
||||
@@ -242,6 +262,30 @@ export default class Store extends EventEmitter {
|
||||
return null;
|
||||
}
|
||||
|
||||
getRootIDForElement(id: number): number | null {
|
||||
let current = this._idToElement.get(id);
|
||||
while (current != null) {
|
||||
if (current.parentID === 0) {
|
||||
return current.id;
|
||||
} else {
|
||||
current = this._idToElement.get(current.parentID);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
startProfiling(): void {
|
||||
this._bridge.send('startProfiling');
|
||||
this._isProfiling = false;
|
||||
this.emit('isProfiling');
|
||||
}
|
||||
|
||||
stopProfiling(): void {
|
||||
this._bridge.send('stopProfiling');
|
||||
this._isProfiling = false;
|
||||
this.emit('isProfiling');
|
||||
}
|
||||
|
||||
_takeProfilingSnapshotRecursive = (id: number) => {
|
||||
const element = this.getElementByID(id);
|
||||
if (element !== null) {
|
||||
@@ -267,11 +311,12 @@ export default class Store extends EventEmitter {
|
||||
let haveRootsChanged = false;
|
||||
|
||||
const rendererID = operations[0];
|
||||
const rootID = operations[1];
|
||||
|
||||
if (this._isProfiling) {
|
||||
const profilingOperations = this._profilingOperations.get(rendererID);
|
||||
const profilingOperations = this._profilingOperations.get(rootID);
|
||||
if (profilingOperations == null) {
|
||||
this._profilingOperations.set(rendererID, [operations]);
|
||||
this._profilingOperations.set(rootID, [operations]);
|
||||
} else {
|
||||
profilingOperations.push(operations);
|
||||
}
|
||||
@@ -280,7 +325,7 @@ export default class Store extends EventEmitter {
|
||||
let addedElementIDs: Uint32Array = new Uint32Array(0);
|
||||
let removedElementIDs: Uint32Array = new Uint32Array(0);
|
||||
|
||||
let i = 1;
|
||||
let i = 2;
|
||||
while (i < operations.length) {
|
||||
let id: number = ((null: any): number);
|
||||
let element: Element = ((null: any): Element);
|
||||
@@ -482,13 +527,16 @@ export default class Store extends EventEmitter {
|
||||
};
|
||||
|
||||
onProfilingStatus = (isProfiling: boolean) => {
|
||||
this._isProfiling = isProfiling;
|
||||
|
||||
if (isProfiling) {
|
||||
this._profilingOperations = new Map();
|
||||
this._profilingSnapshot = new Map();
|
||||
|
||||
this.roots.forEach(this._takeProfilingSnapshotRecursive);
|
||||
}
|
||||
|
||||
if (this._isProfiling !== isProfiling) {
|
||||
this._isProfiling = isProfiling;
|
||||
this.emit('isProfiling');
|
||||
}
|
||||
};
|
||||
|
||||
onBridgeShutdown = () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// @flow
|
||||
|
||||
import React, { Fragment, useCallback, useContext, useState } from 'react';
|
||||
import React, { useCallback, useContext, useState } from 'react';
|
||||
import { ProfilerContext, ProfilerContextController } from './ProfilerContext';
|
||||
import Button from '../Button';
|
||||
import ButtonIcon from '../ButtonIcon';
|
||||
@@ -23,15 +23,15 @@ export default function ProfilerOuter(_: Props) {
|
||||
|
||||
function ProfilerInner(_: Props) {
|
||||
const { hasProfilingData, isProfiling } = useContext(ProfilerContext);
|
||||
|
||||
const showProfilingControls = !isProfiling && hasProfilingData;
|
||||
|
||||
const [tab, setTab] = useState('flame-chart');
|
||||
const [isFilterModalShowing, setIsFilterModalShowing] = useState(false);
|
||||
|
||||
const showFilterModal = useCallback(() => setIsFilterModalShowing(true));
|
||||
const dismissFilterModal = useCallback(() => setIsFilterModalShowing(false));
|
||||
|
||||
// TODO (profiling) Maybe a smarter check here
|
||||
const showProfilingData = !isProfiling && hasProfilingData;
|
||||
|
||||
let view = null;
|
||||
if (isProfiling) {
|
||||
view = <RecortdingInProgress />;
|
||||
@@ -55,7 +55,7 @@ function ProfilerInner(_: Props) {
|
||||
<div className={styles.VRule} />
|
||||
<TabBar
|
||||
currentTab={tab}
|
||||
disabled={!showProfilingData}
|
||||
disabled={!showProfilingControls}
|
||||
id="Profiler"
|
||||
selectTab={setTab}
|
||||
size="small"
|
||||
@@ -65,12 +65,7 @@ function ProfilerInner(_: Props) {
|
||||
<Button onClick={showFilterModal} title="Filter commits by duration">
|
||||
<ButtonIcon type="filter" />
|
||||
</Button>
|
||||
{showProfilingData && (
|
||||
<Fragment>
|
||||
<div className={styles.VRule} />
|
||||
<SnapshotSelector />
|
||||
</Fragment>
|
||||
)}
|
||||
{showProfilingControls && <SnapshotSelector />}
|
||||
</div>
|
||||
<div className={styles.Content}>
|
||||
{view}
|
||||
@@ -79,15 +74,11 @@ function ProfilerInner(_: Props) {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{showProfilingData && (
|
||||
{showProfilingControls && (
|
||||
<div className={styles.RightColumn}>
|
||||
{/* TODO (profiler) Dynamic information */}
|
||||
<div className={styles.Toolbar}>Commit information</div>
|
||||
<div className={styles.InspectedProperties}>
|
||||
Committed at: 0.8s <br />
|
||||
<br />
|
||||
Render duration: 2.1ms
|
||||
</div>
|
||||
<div className={styles.InspectedProperties} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -7,13 +7,18 @@ import React, {
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { BridgeContext, StoreContext } from '../context';
|
||||
|
||||
// TODO (profiling) Connect to store and listen for new roots and load data.
|
||||
import { useSubscription } from '../hooks';
|
||||
import { TreeContext } from 'src/devtools/views/Elements/TreeContext';
|
||||
import { StoreContext } from '../context';
|
||||
import Store from '../../store';
|
||||
|
||||
type Context = {|
|
||||
commitIndex: number,
|
||||
hasProfilingData: boolean,
|
||||
isProfiling: boolean,
|
||||
rendererID: number | null,
|
||||
rootID: number | null,
|
||||
setCommitIndex: (value: number) => void,
|
||||
startProfiling(value: boolean): void,
|
||||
stopProfiling(value: boolean): void,
|
||||
|};
|
||||
@@ -21,33 +26,89 @@ type Context = {|
|
||||
const ProfilerContext = createContext<Context>(((null: any): Context));
|
||||
ProfilerContext.displayName = 'ProfilerContext';
|
||||
|
||||
type StoreProfilingState = {|
|
||||
hasProfilingData: boolean,
|
||||
isProfiling: boolean,
|
||||
|};
|
||||
|
||||
type Props = {|
|
||||
children: React$Node,
|
||||
|};
|
||||
|
||||
function ProfilerContextController({ children }: Props) {
|
||||
const bridge = useContext(BridgeContext);
|
||||
const store = useContext(StoreContext);
|
||||
|
||||
const [isProfiling, setIsProfiling] = useState(false);
|
||||
const { isProfiling, hasProfilingData } = useSubscription<
|
||||
StoreProfilingState,
|
||||
Store
|
||||
>(
|
||||
useMemo(
|
||||
() => ({
|
||||
source: store,
|
||||
getCurrentValue: (store: Store) => ({
|
||||
hasProfilingData: store.hasProfilingData,
|
||||
isProfiling: store.isProfiling,
|
||||
}),
|
||||
subscribe: (store: Store, callback: Function) => {
|
||||
store.addListener('isProfiling', callback);
|
||||
return () => store.removeListener('isProfiling', callback);
|
||||
},
|
||||
}),
|
||||
[store]
|
||||
)
|
||||
);
|
||||
|
||||
const startProfiling = useCallback(() => {
|
||||
bridge.send('startProfiling');
|
||||
setIsProfiling(true);
|
||||
}, [bridge]);
|
||||
const stopProfiling = useCallback(() => {
|
||||
bridge.send('stopProfiling');
|
||||
setIsProfiling(false);
|
||||
}, [bridge]);
|
||||
const startProfiling = useCallback(() => store.startProfiling(), [store]);
|
||||
const stopProfiling = useCallback(() => store.stopProfiling(), [store]);
|
||||
|
||||
// TODO (profiling) The browser extension is a multi-root app,
|
||||
// so ti won't work for the "Profiling" root to depend on a value that's set by the "Elements" root.
|
||||
// We'll either need to lift that state up into the (shared) Store,
|
||||
// or use a portal to share the contexts themselves between Chrome tabs.
|
||||
const { selectedElementID } = useContext(TreeContext);
|
||||
|
||||
// If no root is selected, assume the first root.
|
||||
// Many React apps are single root anyway.
|
||||
let rendererID = null;
|
||||
let rootID = null;
|
||||
if (selectedElementID) {
|
||||
rendererID = store.getRendererIDForElement(
|
||||
((selectedElementID: any): number)
|
||||
);
|
||||
rootID = store.getRootIDForElement(((selectedElementID: any): number));
|
||||
} else if (store.roots.length > 0) {
|
||||
rootID = store.roots[0];
|
||||
rendererID = store.getRendererIDForElement(((rootID: any): number));
|
||||
}
|
||||
|
||||
const [commitIndex, setCommitIndex] = useState(0);
|
||||
const [prevRootID, setPrevRootID] = useState(rootID);
|
||||
if (prevRootID !== rootID) {
|
||||
setPrevRootID(rootID);
|
||||
setCommitIndex(0);
|
||||
}
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
hasProfilingData: false, // TODO (profiling) Connect to store and listen for new roots and load data.
|
||||
commitIndex,
|
||||
hasProfilingData,
|
||||
isProfiling,
|
||||
rendererID,
|
||||
rootID,
|
||||
setCommitIndex,
|
||||
startProfiling,
|
||||
stopProfiling,
|
||||
}),
|
||||
[isProfiling, startProfiling, stopProfiling]
|
||||
[
|
||||
commitIndex,
|
||||
hasProfilingData,
|
||||
isProfiling,
|
||||
rendererID,
|
||||
rootID,
|
||||
setCommitIndex,
|
||||
startProfiling,
|
||||
stopProfiling,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -12,3 +12,10 @@
|
||||
.Commits {
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
|
||||
.VRule {
|
||||
height: 20px;
|
||||
width: 1px;
|
||||
background-color: var(--color-border);
|
||||
margin: 0 0.25rem;
|
||||
}
|
||||
@@ -1,26 +1,80 @@
|
||||
// @flow
|
||||
|
||||
import React from 'react';
|
||||
import React, { Fragment, Suspense, useContext } from 'react';
|
||||
import Button from '../Button';
|
||||
import ButtonIcon from '../ButtonIcon';
|
||||
import { StoreContext } from '../context';
|
||||
import { ProfilerContext } from './ProfilerContext';
|
||||
|
||||
import styles from './SnapshotSelector.css';
|
||||
|
||||
export type Props = {||};
|
||||
|
||||
export default function SnapshotSelector(_: Props) {
|
||||
export default function SnapshotSelectorSuspense(_: Props) {
|
||||
return (
|
||||
<div className={styles.SnapshotSelector}>
|
||||
1 / 3
|
||||
<Button className={styles.Button}>
|
||||
<ButtonIcon type="previous" />
|
||||
</Button>
|
||||
<div className={styles.Commits}>
|
||||
[] {/* TODO (profiling) Add FixedSizeList selector */}
|
||||
</div>
|
||||
<Button className={styles.Button}>
|
||||
<ButtonIcon type="next" />
|
||||
</Button>
|
||||
</div>
|
||||
<Suspense fallback={<SnapshotSelectorFallback />}>
|
||||
<SnapshotSelector />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function SnapshotSelector(_: Props) {
|
||||
const { profilingCache } = useContext(StoreContext);
|
||||
const { commitIndex, rendererID, rootID, setCommitIndex } = useContext(
|
||||
ProfilerContext
|
||||
);
|
||||
|
||||
if (rendererID === null || rootID === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// TODO (profiling) Parse the summary into something easier for the views to work with
|
||||
const profilingSummary = profilingCache.ProfilingSummary.read({
|
||||
rendererID: ((rendererID: any): number),
|
||||
rootID: ((rootID: any): number),
|
||||
});
|
||||
|
||||
const numCommits = profilingSummary.commits.length / 2;
|
||||
|
||||
if (numCommits === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const viewNextCommit = () => {
|
||||
setCommitIndex(Math.min(commitIndex + 1, numCommits - 1));
|
||||
};
|
||||
const viewPrevCommit = () => {
|
||||
setCommitIndex(Math.max(commitIndex - 1, 0));
|
||||
};
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<div className={styles.VRule} />
|
||||
<div className={styles.SnapshotSelector}>
|
||||
{commitIndex + 1} / {numCommits}
|
||||
<Button
|
||||
className={styles.Button}
|
||||
disabled={commitIndex <= 0}
|
||||
onClick={viewPrevCommit}
|
||||
>
|
||||
<ButtonIcon type="previous" />
|
||||
</Button>
|
||||
<div className={styles.Commits}>
|
||||
[] {/* TODO (profiling) Add FixedSizeList selector */}
|
||||
</div>
|
||||
<Button
|
||||
className={styles.Button}
|
||||
disabled={commitIndex >= numCommits - 1}
|
||||
onClick={viewNextCommit}
|
||||
>
|
||||
<ButtonIcon type="next" />
|
||||
</Button>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
function SnapshotSelectorFallback() {
|
||||
// TODO (profiling) Better loading UI
|
||||
return <div className={styles.SnapshotSelector}>Loading...</div>;
|
||||
}
|
||||
@@ -27,3 +27,13 @@ export type CommitDetails = {|
|
||||
root: Node,
|
||||
timestamp: number,
|
||||
|};
|
||||
|
||||
export type ProfilingSummary = {|
|
||||
// Tuples of commit time (relative to when profiling started) and duration
|
||||
commits: Array<number>,
|
||||
|
||||
// Map of fiber id to (initial) tree base duration
|
||||
initialTreeBaseDurations: Map<number, number>,
|
||||
|
||||
interactionCount: number,
|
||||
|};
|
||||
@@ -83,3 +83,59 @@ export function useModalDismissSignal(
|
||||
};
|
||||
}, [modalRef, dismissCallback]);
|
||||
}
|
||||
|
||||
// Copied from https://github.com/facebook/react/pull/15022
|
||||
export function useSubscription<Value, Source>({
|
||||
source,
|
||||
getCurrentValue,
|
||||
subscribe,
|
||||
}: {|
|
||||
source: Source,
|
||||
getCurrentValue: (source: Source) => Value,
|
||||
subscribe: (source: Source, callback: Function) => () => void,
|
||||
|}): Value {
|
||||
const [state, setState] = useState({
|
||||
source,
|
||||
value: getCurrentValue(source),
|
||||
});
|
||||
|
||||
if (state.source !== source) {
|
||||
setState({
|
||||
source,
|
||||
value: getCurrentValue(source),
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let didUnsubscribe = false;
|
||||
|
||||
const checkForUpdates = () => {
|
||||
if (didUnsubscribe) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(prevState => {
|
||||
if (prevState.source !== source) {
|
||||
return prevState;
|
||||
}
|
||||
|
||||
const value = getCurrentValue(source);
|
||||
if (prevState.value === value) {
|
||||
return prevState;
|
||||
}
|
||||
|
||||
return { ...prevState, value };
|
||||
});
|
||||
};
|
||||
const unsubscribe = subscribe(source, checkForUpdates);
|
||||
|
||||
checkForUpdates();
|
||||
|
||||
return () => {
|
||||
didUnsubscribe = true;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [getCurrentValue, source, subscribe]);
|
||||
|
||||
return state.value;
|
||||
}
|
||||
Reference in new issue
Block a user