-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathindex.js
More file actions
498 lines (446 loc) · 15 KB
/
index.js
File metadata and controls
498 lines (446 loc) · 15 KB
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
/**
* 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 Agent from 'react-devtools-shared/src/backend/agent';
import {hideOverlay, showOverlay} from './Highlighter';
import {isReactNativeEnvironment} from 'react-devtools-shared/src/backend/utils';
import type {HostInstance} from 'react-devtools-shared/src/backend/types';
import type {BackendBridge} from 'react-devtools-shared/src/bridge';
import type {RendererInterface} from '../../types';
// This plug-in provides in-page highlighting of the selected element.
// It is used by the browser extension and the standalone DevTools shell (when connected to a browser).
// It is not currently the mechanism used to highlight React Native views.
// That is done by the React Native Inspector component.
let iframesListeningTo: Set<HTMLIFrameElement> = new Set();
let inspectOnlySuspenseNodes = false;
export default function setupHighlighter(
bridge: BackendBridge,
agent: Agent,
): void {
bridge.addListener('clearHostInstanceHighlight', clearHostInstanceHighlight);
bridge.addListener('highlightHostInstance', highlightHostInstance);
bridge.addListener('highlightHostInstances', highlightHostInstances);
bridge.addListener('scrollToHostInstance', scrollToHostInstance);
bridge.addListener('shutdown', stopInspectingHost);
bridge.addListener('startInspectingHost', startInspectingHost);
bridge.addListener('stopInspectingHost', stopInspectingHost);
bridge.addListener('scrollTo', scrollDocumentTo);
bridge.addListener('requestScrollPosition', sendScroll);
let applyingScroll = false;
function scrollDocumentTo({
left,
top,
right,
bottom,
}: {
left: number,
top: number,
right: number,
bottom: number,
}) {
if (isReactNativeEnvironment()) {
// Not implemented.
return;
}
if (
left === Math.round(window.scrollX) &&
top === Math.round(window.scrollY)
) {
return;
}
applyingScroll = true;
window.scrollTo({
top: top,
left: left,
behavior: 'smooth',
});
}
let scrollTimer = null;
function sendScroll() {
if (isReactNativeEnvironment()) {
// Not implemented.
return;
}
if (scrollTimer) {
clearTimeout(scrollTimer);
scrollTimer = null;
}
if (applyingScroll) {
return;
}
const left = window.scrollX;
const top = window.scrollY;
const right = left + window.innerWidth;
const bottom = top + window.innerHeight;
bridge.send('scrollTo', {left, top, right, bottom});
}
function scrollEnd() {
// Upon scrollend send it immediately.
sendScroll();
applyingScroll = false;
}
// $FlowFixMe[method-unbinding]
if (document && typeof document.addEventListener === 'function') {
document.addEventListener('scroll', () => {
if (!scrollTimer) {
// Periodically synchronize the scroll while scrolling.
scrollTimer = setTimeout(sendScroll, 400);
}
});
document.addEventListener('scrollend', scrollEnd);
}
function startInspectingHost(onlySuspenseNodes: boolean) {
inspectOnlySuspenseNodes = onlySuspenseNodes;
registerListenersOnWindow(window);
}
function registerListenersOnWindow(window: any) {
// This plug-in may run in non-DOM environments (e.g. React Native).
if (window && typeof window.addEventListener === 'function') {
window.addEventListener('click', onClick, true);
window.addEventListener('mousedown', onMouseEvent, true);
window.addEventListener('mouseover', onMouseEvent, true);
window.addEventListener('mouseup', onMouseEvent, true);
window.addEventListener('pointerdown', onPointerDown, true);
window.addEventListener('pointermove', onPointerMove, true);
window.addEventListener('pointerup', onPointerUp, true);
} else {
agent.emit('startInspectingNative');
}
}
function stopInspectingHost() {
hideOverlay(agent);
removeListenersOnWindow(window);
iframesListeningTo.forEach(function (frame) {
try {
removeListenersOnWindow(frame.contentWindow);
} catch (error) {
// This can error when the iframe is on a cross-origin.
}
});
iframesListeningTo = new Set();
}
function removeListenersOnWindow(window: any) {
// This plug-in may run in non-DOM environments (e.g. React Native).
if (window && typeof window.removeEventListener === 'function') {
window.removeEventListener('click', onClick, true);
window.removeEventListener('mousedown', onMouseEvent, true);
window.removeEventListener('mouseover', onMouseEvent, true);
window.removeEventListener('mouseup', onMouseEvent, true);
window.removeEventListener('pointerdown', onPointerDown, true);
window.removeEventListener('pointermove', onPointerMove, true);
window.removeEventListener('pointerup', onPointerUp, true);
} else {
agent.emit('stopInspectingNative');
}
}
function clearHostInstanceHighlight() {
hideOverlay(agent);
}
function highlightHostInstance({
displayName,
hideAfterTimeout,
id,
openBuiltinElementsPanel,
rendererID,
scrollIntoView,
}: {
displayName: string | null,
hideAfterTimeout: boolean,
id: number,
openBuiltinElementsPanel: boolean,
rendererID: number,
scrollIntoView: boolean,
...
}) {
const renderer = agent.rendererInterfaces[rendererID];
if (renderer == null) {
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
hideOverlay(agent);
return;
}
// In some cases fiber may already be unmounted
if (!renderer.hasElementWithId(id)) {
hideOverlay(agent);
return;
}
const nodes = renderer.findHostInstancesForElementID(id);
if (nodes != null) {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node === null) {
continue;
}
const nodeRects =
// $FlowFixMe[method-unbinding]
typeof node.getClientRects === 'function'
? node.getClientRects()
: [];
if (
typeof node.getClientRects === 'undefined' || // If Host doesn't implement getClientRects, try to show the overlay.
(nodeRects.length > 0 && // If this is currently display: none, then try another node.
(nodeRects.length > 2 || // This can happen when one of the host instances is a hoistable.
nodeRects[0].width > 0 ||
nodeRects[0].height > 0))
) {
// $FlowFixMe[method-unbinding]
if (scrollIntoView && typeof node.scrollIntoView === 'function') {
if (scrollDelayTimer) {
clearTimeout(scrollDelayTimer);
scrollDelayTimer = null;
}
// If the node isn't visible show it before highlighting it.
// We may want to reconsider this; it might be a little disruptive.
node.scrollIntoView({block: 'nearest', inline: 'nearest'});
}
showOverlay(nodes, displayName, agent, hideAfterTimeout);
if (openBuiltinElementsPanel) {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0 = node;
bridge.send('syncSelectionToBuiltinElementsPanel');
}
return;
}
}
}
hideOverlay(agent);
}
function highlightHostInstances({
displayName,
hideAfterTimeout,
elements,
scrollIntoView,
}: {
displayName: string | null,
hideAfterTimeout: boolean,
elements: Array<{rendererID: number, id: number}>,
scrollIntoView: boolean,
}) {
const nodes: Array<HostInstance> = [];
for (let i = 0; i < elements.length; i++) {
const {id, rendererID} = elements[i];
const renderer = agent.rendererInterfaces[rendererID];
if (renderer == null) {
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
continue;
}
// In some cases fiber may already be unmounted
if (!renderer.hasElementWithId(id)) {
continue;
}
const hostInstances = renderer.findHostInstancesForElementID(id);
if (hostInstances !== null) {
for (let j = 0; j < hostInstances.length; j++) {
nodes.push(hostInstances[j]);
}
}
}
if (nodes.length > 0) {
const node = nodes[0];
// $FlowFixMe[method-unbinding]
if (scrollIntoView && typeof node.scrollIntoView === 'function') {
// If the node isn't visible show it before highlighting it.
// We may want to reconsider this; it might be a little disruptive.
node.scrollIntoView({block: 'nearest', inline: 'nearest'});
}
}
showOverlay(nodes, displayName, agent, hideAfterTimeout);
}
function attemptScrollToHostInstance(
renderer: RendererInterface,
id: number,
) {
const nodes = renderer.findHostInstancesForElementID(id);
if (nodes != null) {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node === null) {
continue;
}
const nodeRects =
// $FlowFixMe[method-unbinding]
typeof node.getClientRects === 'function'
? node.getClientRects()
: [];
// If this is currently display: none, then try another node.
// This can happen when one of the host instances is a hoistable.
if (
nodeRects.length > 0 &&
(nodeRects.length > 2 ||
nodeRects[0].width > 0 ||
nodeRects[0].height > 0)
) {
// $FlowFixMe[method-unbinding]
if (typeof node.scrollIntoView === 'function') {
node.scrollIntoView({
block: 'nearest',
inline: 'nearest',
behavior: 'smooth',
});
return true;
}
}
}
}
return false;
}
let scrollDelayTimer = null;
function scrollToHostInstance({
id,
rendererID,
}: {
id: number,
rendererID: number,
}) {
// Always hide the existing overlay so it doesn't obscure the element.
// If you wanted to show the overlay, highlightHostInstance should be used instead
// with the scrollIntoView option.
hideOverlay(agent);
if (isReactNativeEnvironment()) {
// Not implemented.
return;
}
if (scrollDelayTimer) {
clearTimeout(scrollDelayTimer);
scrollDelayTimer = null;
}
const renderer = agent.rendererInterfaces[rendererID];
if (renderer == null) {
console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`);
return;
}
// In some cases fiber may already be unmounted
if (!renderer.hasElementWithId(id)) {
return;
}
if (attemptScrollToHostInstance(renderer, id)) {
return;
}
// It's possible that the current state of a Suspense boundary doesn't have a position
// in the tree. E.g. because it's not yet mounted in the state we're moving to.
// Such as if it's in a null tree or inside another boundary's hidden state.
// In this case we use the last known position and try to scroll to that.
const rects = renderer.findLastKnownRectsForID(id);
if (rects !== null && rects.length > 0) {
let x = Infinity;
let y = Infinity;
for (let i = 0; i < rects.length; i++) {
const rect = rects[i];
if (rect.x < x) {
x = rect.x;
}
if (rect.y < y) {
y = rect.y;
}
}
const element = document.documentElement;
if (!element) {
return;
}
// Check if the target corner is already in the viewport.
if (
x < window.scrollX ||
y < window.scrollY ||
x > window.scrollX + element.clientWidth ||
y > window.scrollY + element.clientHeight
) {
window.scrollTo({
top: y,
left: x,
behavior: 'smooth',
});
}
// It's possible that after mount, we're able to scroll deeper once the new nodes
// have mounted. Let's try again after mount. Ideally we'd know which commit this
// is going to be but for now we just try after 100ms.
scrollDelayTimer = setTimeout(() => {
attemptScrollToHostInstance(renderer, id);
}, 100);
}
}
function onClick(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
stopInspectingHost();
bridge.send('stopInspectingHost', true);
}
function onMouseEvent(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
}
function onPointerDown(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
selectElementForNode(getEventTarget(event));
}
let lastHoveredNode: HTMLElement | null = null;
function onPointerMove(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
const target: HTMLElement = getEventTarget(event);
if (lastHoveredNode === target) return;
lastHoveredNode = target;
if (target.tagName === 'IFRAME') {
const iframe: HTMLIFrameElement = (target: any);
try {
if (!iframesListeningTo.has(iframe)) {
const window = iframe.contentWindow;
registerListenersOnWindow(window);
iframesListeningTo.add(iframe);
}
} catch (error) {
// This can error when the iframe is on a cross-origin.
}
}
if (inspectOnlySuspenseNodes) {
// For Suspense nodes we want to highlight not the actual target but the nodes
// that are the root of the Suspense node.
// TODO: Consider if we should just do the same for other elements because the
// hovered node might just be one child of many in the Component.
const match = agent.getIDForHostInstance(
target,
inspectOnlySuspenseNodes,
);
if (match !== null) {
const renderer = agent.rendererInterfaces[match.rendererID];
if (renderer == null) {
console.warn(
`Invalid renderer id "${match.rendererID}" for element "${match.id}"`,
);
return;
}
highlightHostInstance({
displayName: renderer.getDisplayNameForElementID(match.id),
hideAfterTimeout: false,
id: match.id,
openBuiltinElementsPanel: false,
rendererID: match.rendererID,
scrollIntoView: false,
});
}
} else {
// Don't pass the name explicitly.
// It will be inferred from DOM tag and Fiber owner.
showOverlay([target], null, agent, false);
}
}
function onPointerUp(event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
}
const selectElementForNode = (node: HTMLElement) => {
const match = agent.getIDForHostInstance(node, inspectOnlySuspenseNodes);
if (match !== null) {
bridge.send('selectElement', match.id);
}
};
function getEventTarget(event: MouseEvent): HTMLElement {
if (event.composed) {
return (event.composedPath()[0]: any);
}
return (event.target: any);
}
}