From b8a52078c6cd273a981caf3dc9d7762624d77391 Mon Sep 17 00:00:00 2001 From: Brian Vaughn Date: Tue, 12 Mar 2019 15:50:29 -0700 Subject: [PATCH] Added initial Suspense cache and loaded commit metadata --- OVERVIEW.md | 8 +- src/backend/agent.js | 21 ++- src/backend/renderer.js | 111 ++++++++++--- src/backend/types.js | 8 + src/devtools/ProfilingCache.js | 77 +++++++++ src/devtools/cache.js | 146 ++++++++++++++++++ src/devtools/store.js | 62 +++++++- src/devtools/views/Profiler/Profiler.js | 25 +-- .../views/Profiler/ProfilerContext.js | 91 +++++++++-- .../views/Profiler/SnapshotSelector.css | 7 + .../views/Profiler/SnapshotSelector.js | 82 ++++++++-- src/devtools/views/Profiler/types.js | 10 ++ src/devtools/views/hooks.js | 56 +++++++ 13 files changed, 624 insertions(+), 80 deletions(-) create mode 100644 src/devtools/ProfilingCache.js create mode 100644 src/devtools/cache.js diff --git a/OVERVIEW.md b/OVERVIEW.md index 29a5345c46..b6d68549a5 100644 --- a/OVERVIEW.md +++ b/OVERVIEW.md @@ -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. \ No newline at end of file +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. \ No newline at end of file diff --git a/src/backend/agent.js b/src/backend/agent.js index 59169d0643..b7df24d42f 100644 --- a/src/backend/agent.js +++ b/src/backend/agent.js @@ -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); }; diff --git a/src/backend/renderer.js b/src/backend/renderer.js index 7c63a79b7d..398b4cfba3 100644 --- a/src/backend/renderer.js +++ b/src/backend/renderer.js @@ -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 = 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 = 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).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, commitTime: number, interactions: Array, + maxActualDuration: number, |}; - let commitProfilingMetadata: Array | null = null; + type CommitProfilingMetadataMap = Map>; + let currentCommitProfilingMetadata: CommitProfilingData | null = null; - let initialTreeBaseDurations: Array | null = null; + let initialTreeBaseDurationsMap: Map | 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).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, diff --git a/src/backend/types.js b/src/backend/types.js index 0b3521b2cd..11869ab179 100644 --- a/src/backend/types.js +++ b/src/backend/types.js @@ -54,6 +54,13 @@ export type ReactRenderer = { currentDispatcherRef?: {| current: null | Dispatcher |}, }; +export type ProfilingSummary = {| + commits: Array, + initialTreeBaseDurations: Array, + 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, diff --git a/src/devtools/ProfilingCache.js b/src/devtools/ProfilingCache.js new file mode 100644 index 0000000000..68982b081c --- /dev/null +++ b/src/devtools/ProfilingCache.js @@ -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; + + // 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, + }); + } + }; +} diff --git a/src/devtools/cache.js b/src/devtools/cache.js new file mode 100644 index 0000000000..92df88a37a --- /dev/null +++ b/src/devtools/cache.js @@ -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 = { + then(resolve: (T) => mixed, reject: (mixed) => mixed): mixed, +}; + +type Suspender = { + then(resolve: () => mixed, reject: () => mixed): mixed, +}; + +type PendingResult = {| + status: 0, + value: Suspender, +|}; + +type ResolvedResult = {| + status: 1, + value: V, +|}; + +type RejectedResult = {| + status: 2, + value: mixed, +|}; + +type Result = PendingResult | ResolvedResult | RejectedResult; + +export type Resource = { + 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, Map> = new Map(); + +function accessResult( + resource: any, + fetch: I => Thenable, + input: I, + key: K +): Result { + 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 = (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( + fetch: I => Thenable, + maybeHashInput?: I => K +): Resource { + 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 = 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(); +} diff --git a/src/devtools/store.js b/src/devtools/store.js index 334eecbe34..4f733df1e6 100644 --- a/src/devtools/store.js +++ b/src/devtools/store.js @@ -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 = 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> = 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 = () => { diff --git a/src/devtools/views/Profiler/Profiler.js b/src/devtools/views/Profiler/Profiler.js index 8cc1e54aa5..af11db8e10 100644 --- a/src/devtools/views/Profiler/Profiler.js +++ b/src/devtools/views/Profiler/Profiler.js @@ -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 = ; @@ -55,7 +55,7 @@ function ProfilerInner(_: Props) {
- {showProfilingData && ( - -
- - - )} + {showProfilingControls && }
{view} @@ -79,15 +74,11 @@ function ProfilerInner(_: Props) { )}
- {showProfilingData && ( + {showProfilingControls && (
{/* TODO (profiler) Dynamic information */}
Commit information
-
- Committed at: 0.8s
-
- Render duration: 2.1ms -
+
)}
diff --git a/src/devtools/views/Profiler/ProfilerContext.js b/src/devtools/views/Profiler/ProfilerContext.js index a2ff8e89cf..df4f2874d5 100644 --- a/src/devtools/views/Profiler/ProfilerContext.js +++ b/src/devtools/views/Profiler/ProfilerContext.js @@ -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(((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 ( diff --git a/src/devtools/views/Profiler/SnapshotSelector.css b/src/devtools/views/Profiler/SnapshotSelector.css index 96998d93bc..b404d6251d 100644 --- a/src/devtools/views/Profiler/SnapshotSelector.css +++ b/src/devtools/views/Profiler/SnapshotSelector.css @@ -12,3 +12,10 @@ .Commits { margin-left: 0.25rem; } + +.VRule { + height: 20px; + width: 1px; + background-color: var(--color-border); + margin: 0 0.25rem; +} diff --git a/src/devtools/views/Profiler/SnapshotSelector.js b/src/devtools/views/Profiler/SnapshotSelector.js index 64d68b109e..091ffd3441 100644 --- a/src/devtools/views/Profiler/SnapshotSelector.js +++ b/src/devtools/views/Profiler/SnapshotSelector.js @@ -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 ( -
- 1 / 3 - -
- [] {/* TODO (profiling) Add FixedSizeList selector */} -
- -
+ }> + + ); } + +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 ( + +
+
+ {commitIndex + 1} / {numCommits} + +
+ [] {/* TODO (profiling) Add FixedSizeList selector */} +
+ +
+ + ); +} + +function SnapshotSelectorFallback() { + // TODO (profiling) Better loading UI + return
Loading...
; +} diff --git a/src/devtools/views/Profiler/types.js b/src/devtools/views/Profiler/types.js index 78dd15abb4..e75a369da3 100644 --- a/src/devtools/views/Profiler/types.js +++ b/src/devtools/views/Profiler/types.js @@ -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, + + // Map of fiber id to (initial) tree base duration + initialTreeBaseDurations: Map, + + interactionCount: number, +|}; diff --git a/src/devtools/views/hooks.js b/src/devtools/views/hooks.js index 0218aef2e6..3315ce6021 100644 --- a/src/devtools/views/hooks.js +++ b/src/devtools/views/hooks.js @@ -83,3 +83,59 @@ export function useModalDismissSignal( }; }, [modalRef, dismissCallback]); } + +// Copied from https://github.com/facebook/react/pull/15022 +export function useSubscription({ + 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; +}