forked from facebook/react
/
InspectedElementContext.js
372 lines (324 loc) · 10.8 KB
/
InspectedElementContext.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import {unstable_batchedUpdates as batchedUpdates} from 'react-dom';
import {createResource} from '../../cache';
import {BridgeContext, StoreContext} from '../context';
import {hydrate, fillInPath} from 'react-devtools-shared/src/hydration';
import {TreeStateContext} from './TreeContext';
import {separateDisplayNameAndHOCs} from 'react-devtools-shared/src/utils';
import type {
InspectedElement as InspectedElementBackend,
InspectedElementPayload,
} from 'react-devtools-shared/src/backend/types';
import type {
DehydratedData,
Element,
InspectedElement as InspectedElementFrontend,
} from 'react-devtools-shared/src/devtools/views/Components/types';
import type {Resource, Thenable} from '../../cache';
export type StoreAsGlobal = (id: number, path: Array<string | number>) => void;
export type CopyInspectedElementPath = (
id: number,
path: Array<string | number>,
) => void;
export type GetInspectedElementPath = (
id: number,
path: Array<string | number>,
) => void;
export type GetInspectedElement = (
id: number,
) => InspectedElementFrontend | null;
type Context = {|
copyInspectedElementPath: CopyInspectedElementPath,
getInspectedElementPath: GetInspectedElementPath,
getInspectedElement: GetInspectedElement,
storeAsGlobal: StoreAsGlobal,
|};
const InspectedElementContext = createContext<Context>(((null: any): Context));
InspectedElementContext.displayName = 'InspectedElementContext';
type ResolveFn = (inspectedElement: InspectedElementFrontend) => void;
type InProgressRequest = {|
promise: Thenable<InspectedElementFrontend>,
resolveFn: ResolveFn,
|};
const inProgressRequests: WeakMap<Element, InProgressRequest> = new WeakMap();
const resource: Resource<
Element,
Element,
InspectedElementFrontend,
> = createResource(
(element: Element) => {
let request = inProgressRequests.get(element);
if (request != null) {
return request.promise;
}
let resolveFn = ((null: any): ResolveFn);
const promise = new Promise(resolve => {
resolveFn = resolve;
});
inProgressRequests.set(element, {promise, resolveFn});
return promise;
},
(element: Element) => element,
{useWeakMap: true},
);
type Props = {|
children: React$Node,
|};
function InspectedElementContextController({children}: Props) {
const bridge = useContext(BridgeContext);
const store = useContext(StoreContext);
const storeAsGlobalCount = useRef(1);
// Ask the backend to store the value at the specified path as a global variable.
const storeAsGlobal = useCallback<GetInspectedElementPath>(
(id: number, path: Array<string | number>) => {
const rendererID = store.getRendererIDForElement(id);
if (rendererID !== null) {
bridge.send('storeAsGlobal', {
count: storeAsGlobalCount.current++,
id,
path,
rendererID,
});
}
},
[bridge, store],
);
// Ask the backend to copy the specified path to the clipboard.
const copyInspectedElementPath = useCallback<GetInspectedElementPath>(
(id: number, path: Array<string | number>) => {
const rendererID = store.getRendererIDForElement(id);
if (rendererID !== null) {
bridge.send('copyElementPath', {id, path, rendererID});
}
},
[bridge, store],
);
// Ask the backend to fill in a "dehydrated" path; this will result in a "inspectedElement".
const getInspectedElementPath = useCallback<GetInspectedElementPath>(
(id: number, path: Array<string | number>) => {
const rendererID = store.getRendererIDForElement(id);
if (rendererID !== null) {
bridge.send('inspectElement', {id, path, rendererID});
}
},
[bridge, store],
);
const getInspectedElement = useCallback<GetInspectedElement>(
(id: number) => {
const element = store.getElementByID(id);
if (element !== null) {
return resource.read(element);
} else {
return null;
}
},
[store],
);
// It's very important that this context consumes selectedElementID and not inspectedElementID.
// Otherwise the effect that sends the "inspect" message across the bridge-
// would itself be blocked by the same render that suspends (waiting for the data).
const {selectedElementID} = useContext(TreeStateContext);
const [
currentlyInspectedElement,
setCurrentlyInspectedElement,
] = useState<InspectedElementFrontend | null>(null);
// This effect handler invalidates the suspense cache and schedules rendering updates with React.
useEffect(() => {
const onInspectedElement = (data: InspectedElementPayload) => {
const {id} = data;
let element;
switch (data.type) {
case 'no-change':
case 'not-found':
// No-op
break;
case 'hydrated-path':
// Merge new data into previous object and invalidate cache
element = store.getElementByID(id);
if (element !== null) {
if (currentlyInspectedElement != null) {
const value = hydrateHelper(data.value, data.path);
const inspectedElement = {...currentlyInspectedElement};
fillInPath(inspectedElement, data.value, data.path, value);
resource.write(element, inspectedElement);
// Schedule update with React if the curently-selected element has been invalidated.
if (id === selectedElementID) {
setCurrentlyInspectedElement(inspectedElement);
}
}
}
break;
case 'full-data':
const {
canEditFunctionProps,
canEditHooks,
canToggleSuspense,
canViewSource,
hasLegacyContext,
source,
type,
owners,
context,
hooks,
props,
state,
} = ((data.value: any): InspectedElementBackend);
const inspectedElement: InspectedElementFrontend = {
canEditFunctionProps,
canEditHooks,
canToggleSuspense,
canViewSource,
hasLegacyContext,
id,
source,
type,
owners:
owners === null
? null
: owners.map(owner => {
const [
displayName,
hocDisplayNames,
] = separateDisplayNameAndHOCs(
owner.displayName,
owner.type,
);
return {
...owner,
displayName,
hocDisplayNames,
};
}),
context: hydrateHelper(context),
hooks: hydrateHelper(hooks),
props: hydrateHelper(props),
state: hydrateHelper(state),
};
element = store.getElementByID(id);
if (element !== null) {
const request = inProgressRequests.get(element);
if (request != null) {
inProgressRequests.delete(element);
batchedUpdates(() => {
request.resolveFn(inspectedElement);
setCurrentlyInspectedElement(inspectedElement);
});
} else {
resource.write(element, inspectedElement);
// Schedule update with React if the curently-selected element has been invalidated.
if (id === selectedElementID) {
setCurrentlyInspectedElement(inspectedElement);
}
}
}
break;
default:
break;
}
};
bridge.addListener('inspectedElement', onInspectedElement);
return () => bridge.removeListener('inspectedElement', onInspectedElement);
}, [bridge, currentlyInspectedElement, selectedElementID, store]);
// This effect handler polls for updates on the currently selected element.
useEffect(() => {
if (selectedElementID === null) {
return () => {};
}
const rendererID = store.getRendererIDForElement(selectedElementID);
let timeoutID: TimeoutID | null = null;
const sendRequest = () => {
timeoutID = null;
if (rendererID !== null) {
bridge.send('inspectElement', {id: selectedElementID, rendererID});
}
};
// Send the initial inspection request.
// We'll poll for an update in the response handler below.
sendRequest();
const onInspectedElement = (data: InspectedElementPayload) => {
// If this is the element we requested, wait a little bit and then ask for another update.
if (data.id === selectedElementID) {
switch (data.type) {
case 'no-change':
case 'full-data':
case 'hydrated-path':
if (timeoutID !== null) {
clearTimeout(timeoutID);
}
timeoutID = setTimeout(sendRequest, 1000);
break;
default:
break;
}
}
};
bridge.addListener('inspectedElement', onInspectedElement);
return () => {
bridge.removeListener('inspectedElement', onInspectedElement);
if (timeoutID !== null) {
clearTimeout(timeoutID);
}
};
}, [bridge, selectedElementID, store]);
const value = useMemo(
() => ({
copyInspectedElementPath,
getInspectedElement,
getInspectedElementPath,
storeAsGlobal,
}),
// InspectedElement is used to invalidate the cache and schedule an update with React.
[
copyInspectedElementPath,
currentlyInspectedElement,
getInspectedElement,
getInspectedElementPath,
storeAsGlobal,
],
);
return (
<InspectedElementContext.Provider value={value}>
{children}
</InspectedElementContext.Provider>
);
}
function hydrateHelper(
dehydratedData: DehydratedData | null,
path?: Array<string | number>,
): Object | null {
if (dehydratedData !== null) {
let {cleaned, data, unserializable} = dehydratedData;
if (path) {
const {length} = path;
if (length > 0) {
// Hydration helper requires full paths, but inspection dehydrates with relative paths.
// In that event it's important that we adjust the "cleaned" paths to match.
cleaned = cleaned.map(cleanedPath => cleanedPath.slice(length));
unserializable = unserializable.map(unserializablePath =>
unserializablePath.slice(length),
);
}
}
return hydrate(data, cleaned, unserializable);
} else {
return null;
}
}
export {InspectedElementContext, InspectedElementContextController};