-
Notifications
You must be signed in to change notification settings - Fork 48.4k
/
Copy pathinspectedElementCache.js
291 lines (246 loc) · 7.23 KB
/
inspectedElementCache.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
/**
* Copyright (c) Meta Platforms, Inc. and 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 {
unstable_getCacheForType as getCacheForType,
startTransition,
} from 'react';
import Store from 'react-devtools-shared/src/devtools/store';
import {inspectElement as inspectElementMutableSource} from 'react-devtools-shared/src/inspectedElementMutableSource';
import ElementPollingCancellationError from 'react-devtools-shared/src//errors/ElementPollingCancellationError';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type {Wakeable} from 'shared/ReactTypes';
import type {
Element,
InspectedElement as InspectedElementFrontend,
InspectedElementResponseType,
InspectedElementPath,
} from 'react-devtools-shared/src/frontend/types';
const Pending = 0;
const Resolved = 1;
const Rejected = 2;
type PendingRecord = {
status: 0,
value: Wakeable,
};
type ResolvedRecord<T> = {
status: 1,
value: T,
};
type RejectedRecord = {
status: 2,
value: Error | string,
};
type Record<T> = PendingRecord | ResolvedRecord<T> | RejectedRecord;
function readRecord<T>(record: Record<T>): ResolvedRecord<T> {
if (record.status === Resolved) {
// This is just a type refinement.
return record;
} else {
throw record.value;
}
}
type InspectedElementMap = WeakMap<Element, Record<InspectedElementFrontend>>;
type CacheSeedKey = () => InspectedElementMap;
function createMap(): InspectedElementMap {
return new WeakMap();
}
function getRecordMap(): WeakMap<Element, Record<InspectedElementFrontend>> {
return getCacheForType(createMap);
}
function createCacheSeed(
element: Element,
inspectedElement: InspectedElementFrontend,
): [CacheSeedKey, InspectedElementMap] {
const newRecord: Record<InspectedElementFrontend> = {
status: Resolved,
value: inspectedElement,
};
const map = createMap();
map.set(element, newRecord);
return [createMap, map];
}
/**
* Fetches element props and state from the backend for inspection.
* This method should be called during render; it will suspend if data has not yet been fetched.
*/
export function inspectElement(
element: Element,
path: InspectedElementPath | null,
store: Store,
bridge: FrontendBridge,
): InspectedElementFrontend | null {
const map = getRecordMap();
let record = map.get(element);
if (!record) {
const callbacks = new Set<() => mixed>();
const wakeable: Wakeable = {
then(callback: () => mixed) {
callbacks.add(callback);
},
// Optional property used by Timeline:
displayName: `Inspecting ${element.displayName || 'Unknown'}`,
};
const wake = () => {
// This assumes they won't throw.
callbacks.forEach(callback => callback());
callbacks.clear();
};
const newRecord: Record<InspectedElementFrontend> = (record = {
status: Pending,
value: wakeable,
});
const rendererID = store.getRendererIDForElement(element.id);
if (rendererID == null) {
const rejectedRecord = ((newRecord: any): RejectedRecord);
rejectedRecord.status = Rejected;
rejectedRecord.value = new Error(
`Could not inspect element with id "${element.id}". No renderer found.`,
);
map.set(element, record);
return null;
}
inspectElementMutableSource(bridge, element, path, rendererID).then(
([inspectedElement]: [
InspectedElementFrontend,
InspectedElementResponseType,
]) => {
const resolvedRecord =
((newRecord: any): ResolvedRecord<InspectedElementFrontend>);
resolvedRecord.status = Resolved;
resolvedRecord.value = inspectedElement;
wake();
},
error => {
console.error(error);
const rejectedRecord = ((newRecord: any): RejectedRecord);
rejectedRecord.status = Rejected;
rejectedRecord.value = error;
wake();
},
);
map.set(element, record);
}
const response = readRecord(record).value;
return response;
}
type RefreshFunction = (
seedKey: CacheSeedKey,
cacheMap: InspectedElementMap,
) => void;
/**
* Asks the backend for updated props and state from an expected element.
* This method should never be called during render; call it from an effect or event handler.
* This method will schedule an update if updated information is returned.
*/
export function checkForUpdate({
bridge,
element,
refresh,
store,
}: {
bridge: FrontendBridge,
element: Element,
refresh: RefreshFunction,
store: Store,
}): void | Promise<void> {
const {id} = element;
const rendererID = store.getRendererIDForElement(id);
if (rendererID == null) {
return;
}
return inspectElementMutableSource(
bridge,
element,
null,
rendererID,
true,
).then(
([inspectedElement, responseType]: [
InspectedElementFrontend,
InspectedElementResponseType,
]) => {
if (responseType === 'full-data') {
startTransition(() => {
const [key, value] = createCacheSeed(element, inspectedElement);
refresh(key, value);
});
}
},
);
}
function createPromiseWhichResolvesInOneSecond() {
return new Promise(resolve => setTimeout(resolve, 1000));
}
type PollingStatus = 'idle' | 'running' | 'paused' | 'aborted';
export function startElementUpdatesPolling({
bridge,
element,
refresh,
store,
}: {
bridge: FrontendBridge,
element: Element,
refresh: RefreshFunction,
store: Store,
}): {abort: () => void, pause: () => void, resume: () => void} {
let status: PollingStatus = 'idle';
function abort() {
status = 'aborted';
}
function resume() {
if (status === 'running' || status === 'aborted') {
return;
}
status = 'idle';
poll();
}
function pause() {
if (status === 'paused' || status === 'aborted') {
return;
}
status = 'paused';
}
function poll(): Promise<void> {
status = 'running';
return Promise.allSettled([
checkForUpdate({bridge, element, refresh, store}),
createPromiseWhichResolvesInOneSecond(),
])
.then(([{status: updateStatus, reason}]) => {
// There isn't much to do about errors in this case,
// but we should at least log them, so they aren't silent.
// Log only if polling is still active, we can't handle the case when
// request was sent, and then bridge was remounted (for example, when user did navigate to a new page),
// but at least we can mark that polling was aborted
if (updateStatus === 'rejected' && status !== 'aborted') {
// This is expected Promise rejection, no need to log it
if (reason instanceof ElementPollingCancellationError) {
return;
}
console.error(reason);
}
})
.finally(() => {
const shouldContinuePolling =
status !== 'aborted' && status !== 'paused';
status = 'idle';
if (shouldContinuePolling) {
return poll();
}
});
}
poll();
return {abort, resume, pause};
}
export function clearCacheBecauseOfError(refresh: RefreshFunction): void {
startTransition(() => {
const map = createMap();
refresh(createMap, map);
});
}