-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathTree.js
482 lines (436 loc) · 16 KB
/
Tree.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
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
// @flow
import React, {
Suspense,
useState,
useCallback,
useContext,
useEffect,
useMemo,
useLayoutEffect,
useRef,
} from 'react';
import AutoSizer from 'react-virtualized-auto-sizer';
import { FixedSizeList } from 'react-window';
import { TreeDispatcherContext, TreeStateContext } from './TreeContext';
import { SettingsContext } from '../Settings/SettingsContext';
import { BridgeContext, StoreContext } from '../context';
import ElementView from './Element';
import InspectHostNodesToggle from './InspectHostNodesToggle';
import OwnersStack from './OwnersStack';
import SearchInput from './SearchInput';
import { ComponentFiltersModalContextController } from './ComponentFiltersModalContext';
import ToggleComponentFiltersModalButton from './ToggleComponentFiltersModalButton';
import ComponentFiltersModal from './ComponentFiltersModal';
import Guideline from './Guideline';
import TreeFocusedContext from './TreeFocusedContext';
import styles from './Tree.css';
export type ItemData = {|
numElements: number,
isNavigatingWithKeyboard: boolean,
lastScrolledIDRef: { current: number | null },
onElementMouseEnter: (id: number) => void,
treeFocused: boolean,
|};
// Never indent more than this number of pixels (even if we have the room).
const DEFAULT_INDENTATION_SIZE = 12;
// Never increase indentation by more than this number of pixels in a single adjustment.
// This is to prevent things from "jumping" when a wide item is scrolled out of view.
const MAX_INDENTATION_SIZE_INCREASE = 0.25;
type Props = {||};
export default function Tree(props: Props) {
const dispatch = useContext(TreeDispatcherContext);
const {
numElements,
ownerID,
searchIndex,
searchResults,
selectedElementID,
selectedElementIndex,
} = useContext(TreeStateContext);
const bridge = useContext(BridgeContext);
const store = useContext(StoreContext);
const [isNavigatingWithKeyboard, setIsNavigatingWithKeyboard] = useState(
false
);
// $FlowFixMe https://github.com/facebook/flow/issues/7341
const listRef = useRef<FixedSizeList<ItemData> | null>(null);
const treeRef = useRef<HTMLDivElement | null>(null);
const focusTargetRef = useRef<HTMLDivElement | null>(null);
const [treeFocused, setTreeFocused] = useState<boolean>(false);
const { lineHeight } = useContext(SettingsContext);
// Make sure a newly selected element is visible in the list.
// This is helpful for things like the owners list and search.
useLayoutEffect(() => {
if (selectedElementIndex !== null && listRef.current != null) {
listRef.current.scrollToItem(selectedElementIndex, 'smart');
// Note this autoscroll only works for rows.
// There's another autoscroll inside the elements
// that ensures the component name is visible horizontally.
// It's too early to do it now because the row might not exist yet.
}
}, [listRef, selectedElementIndex]);
// Picking an element in the inspector should put focus into the tree.
// This ensures that keyboard navigation works right after picking a node.
useEffect(() => {
function handleStopInspectingDOM(didSelectNode) {
if (didSelectNode && focusTargetRef.current !== null) {
focusTargetRef.current.focus();
}
}
bridge.addListener('stopInspectingDOM', handleStopInspectingDOM);
return () =>
bridge.removeListener('stopInspectingDOM', handleStopInspectingDOM);
}, [bridge]);
// This ref is passed down the context to elements.
// It lets them avoid autoscrolling to the same item many times
// when a selected virtual row goes in and out of the viewport.
const lastScrolledIDRef = useRef<number | null>(null);
// Navigate the tree with up/down arrow keys.
useEffect(() => {
if (treeRef.current === null) {
return () => {};
}
const handleKeyDown = (event: KeyboardEvent) => {
if ((event: any).target.tagName === 'INPUT' || event.defaultPrevented) {
return;
}
let element;
switch (event.key) {
case 'ArrowDown':
event.preventDefault();
dispatch({ type: 'SELECT_NEXT_ELEMENT_IN_TREE' });
break;
case 'ArrowLeft':
event.preventDefault();
element =
selectedElementID !== null
? store.getElementByID(selectedElementID)
: null;
if (element !== null) {
if (element.children.length > 0 && !element.isCollapsed) {
store.toggleIsCollapsed(element.id, true);
} else {
dispatch({ type: 'SELECT_PARENT_ELEMENT_IN_TREE' });
}
}
break;
case 'ArrowRight':
event.preventDefault();
element =
selectedElementID !== null
? store.getElementByID(selectedElementID)
: null;
if (element !== null) {
if (element.children.length > 0 && element.isCollapsed) {
store.toggleIsCollapsed(element.id, false);
} else {
dispatch({ type: 'SELECT_CHILD_ELEMENT_IN_TREE' });
}
}
break;
case 'ArrowUp':
event.preventDefault();
dispatch({ type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE' });
break;
default:
return;
}
setIsNavigatingWithKeyboard(true);
};
// It's important to listen to the ownerDocument to support the browser extension.
// Here we use portals to render individual tabs (e.g. Profiler),
// and the root document might belong to a different window.
const ownerDocument = treeRef.current.ownerDocument;
ownerDocument.addEventListener('keydown', handleKeyDown);
return () => {
ownerDocument.removeEventListener('keydown', handleKeyDown);
};
}, [dispatch, selectedElementID, store]);
// Focus management.
const handleBlur = useCallback(() => setTreeFocused(false), []);
const handleFocus = useCallback(() => {
setTreeFocused(true);
if (selectedElementIndex === null && numElements > 0) {
dispatch({
type: 'SELECT_ELEMENT_AT_INDEX',
payload: 0,
});
}
}, [dispatch, numElements, selectedElementIndex]);
const handleKeyPress = useCallback(
event => {
switch (event.key) {
case 'Enter':
case ' ':
if (selectedElementID !== null) {
dispatch({ type: 'SELECT_OWNER', payload: selectedElementID });
}
break;
default:
break;
}
},
[dispatch, selectedElementID]
);
const highlightElementInDOM = useCallback(
(id: number) => {
const element = store.getElementByID(id);
const rendererID = store.getRendererIDForElement(id);
if (element !== null) {
bridge.send('highlightElementInDOM', {
displayName: element.displayName,
hideAfterTimeout: false,
id,
openNativeElementsPanel: false,
rendererID,
scrollIntoView: false,
});
}
},
[store, bridge]
);
// If we switch the selected element while using the keyboard,
// start highlighting it in the DOM instead of the last hovered node.
const searchRef = useRef({ searchIndex, searchResults });
useEffect(() => {
let didSelectNewSearchResult = false;
if (
searchRef.current.searchIndex !== searchIndex ||
searchRef.current.searchResults !== searchResults
) {
searchRef.current.searchIndex = searchIndex;
searchRef.current.searchResults = searchResults;
didSelectNewSearchResult = true;
}
if (isNavigatingWithKeyboard || didSelectNewSearchResult) {
if (selectedElementID !== null) {
highlightElementInDOM(selectedElementID);
} else {
bridge.send('clearHighlightedElementInDOM');
}
}
}, [
bridge,
isNavigatingWithKeyboard,
highlightElementInDOM,
searchIndex,
searchResults,
selectedElementID,
]);
// Highlight last hovered element.
const handleElementMouseEnter = useCallback(
id => {
// Ignore hover while we're navigating with keyboard.
// This avoids flicker from the hovered nodes under the mouse.
if (!isNavigatingWithKeyboard) {
highlightElementInDOM(id);
}
},
[isNavigatingWithKeyboard, highlightElementInDOM]
);
const handleMouseMove = useCallback(() => {
// We started using the mouse again.
// This will enable hover styles in individual rows.
setIsNavigatingWithKeyboard(false);
}, []);
const handleMouseLeave = useCallback(() => {
bridge.send('clearHighlightedElementInDOM');
}, [bridge]);
// Let react-window know to re-render any time the underlying tree data changes.
// This includes the owner context, since it controls a filtered view of the tree.
const itemData = useMemo<ItemData>(
() => ({
numElements,
isNavigatingWithKeyboard,
onElementMouseEnter: handleElementMouseEnter,
lastScrolledIDRef,
treeFocused,
}),
[
numElements,
isNavigatingWithKeyboard,
handleElementMouseEnter,
lastScrolledIDRef,
treeFocused,
]
);
const itemKey = useCallback(
(index: number) => store.getElementIDAtIndex(index),
[store]
);
return (
<TreeFocusedContext.Provider value={treeFocused}>
<ComponentFiltersModalContextController>
<div className={styles.Tree} ref={treeRef}>
<div className={styles.SearchInput}>
<InspectHostNodesToggle />
<div className={styles.VRule} />
<Suspense fallback={<Loading />}>
{ownerID !== null ? <OwnersStack /> : <SearchInput />}
</Suspense>
<div className={styles.VRule} />
<ToggleComponentFiltersModalButton />
</div>
<div
className={styles.AutoSizerWrapper}
onBlur={handleBlur}
onFocus={handleFocus}
onKeyPress={handleKeyPress}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
ref={focusTargetRef}
tabIndex={0}
>
<AutoSizer>
{({ height, width }) => (
// $FlowFixMe https://github.com/facebook/flow/issues/7341
<FixedSizeList
className={styles.List}
height={height}
innerElementType={InnerElementType}
itemCount={numElements}
itemData={itemData}
itemKey={itemKey}
itemSize={lineHeight}
ref={listRef}
width={width}
>
{ElementView}
</FixedSizeList>
)}
</AutoSizer>
</div>
<ComponentFiltersModal />
</div>
</ComponentFiltersModalContextController>
</TreeFocusedContext.Provider>
);
}
// Indentation size can be adjusted but child width is fixed.
// We need to adjust indentations so the widest child can fit without overflowing.
// Sometimes the widest child is also the deepest in the tree:
// ┏----------------------┓
// ┆ <Foo> ┆
// ┆ ••••<Foobar> ┆
// ┆ ••••••••<Baz> ┆
// ┗----------------------┛
//
// But this is not always the case.
// Even with the above example, a change in indentation may change the overall widest child:
// ┏----------------------┓
// ┆ <Foo> ┆
// ┆ ••<Foobar> ┆
// ┆ ••••<Baz> ┆
// ┗----------------------┛
//
// In extreme cases this difference can be important:
// ┏----------------------┓
// ┆ <ReallyLongName> ┆
// ┆ ••<Foo> ┆
// ┆ ••••<Bar> ┆
// ┆ ••••••<Baz> ┆
// ┆ ••••••••<Qux> ┆
// ┗----------------------┛
//
// In the above example, the current indentation is fine,
// but if we naively assumed that the widest element is also the deepest element,
// we would end up compressing the indentation unnecessarily:
// ┏----------------------┓
// ┆ <ReallyLongName> ┆
// ┆ •<Foo> ┆
// ┆ ••<Bar> ┆
// ┆ •••<Baz> ┆
// ┆ ••••<Qux> ┆
// ┗----------------------┛
//
// The way we deal with this is to compute the max indentation size that can fit each child,
// given the child's fixed width and depth within the tree.
// Then we take the smallest of these indentation sizes...
function updateIndentationSizeVar(
innerDiv: HTMLDivElement,
cachedChildWidths: WeakMap<HTMLElement, number>,
indentationSizeRef: {| current: number |}
): void {
const list = ((innerDiv.parentElement: any): HTMLDivElement);
const listWidth = list.clientWidth;
let maxIndentationSize: number = DEFAULT_INDENTATION_SIZE;
for (let child of innerDiv.children) {
const depth = parseInt(child.getAttribute('data-depth'), 10) || 0;
let childWidth: number = 0;
const cachedChildWidth = cachedChildWidths.get(child);
if (cachedChildWidth != null) {
childWidth = cachedChildWidth;
} else {
const { firstElementChild } = child;
// Skip over e.g. the guideline element
if (firstElementChild != null) {
childWidth = firstElementChild.clientWidth;
cachedChildWidths.set(child, childWidth);
}
}
const remainingWidth = Math.max(0, listWidth - childWidth);
maxIndentationSize = Math.min(maxIndentationSize, remainingWidth / depth);
}
// It's very important to shrink indentation so that nothing gets clipped.
// But it is less important to increase indentation when something wide is scrolled out of view.
// In fact, increasing too much leads to visual "jumping" which can be unpleasant.
// To avoid this, we only increase by a maximum of some threshold (MAX_INDENTATION_SIZE_INCREASE).
const newIndentationSize =
indentationSizeRef.current > maxIndentationSize
? maxIndentationSize
: Math.min(
maxIndentationSize,
indentationSizeRef.current + MAX_INDENTATION_SIZE_INCREASE
);
list.style.setProperty('--indentation-size', `${newIndentationSize}px`);
indentationSizeRef.current = newIndentationSize;
}
function InnerElementType({ children, style, ...rest }) {
const { ownerID } = useContext(TreeStateContext);
const cachedChildWidths = useMemo<WeakMap<HTMLElement, number>>(
() => new WeakMap(),
[]
);
const indentationSizeRef = useRef<number>(DEFAULT_INDENTATION_SIZE);
// The list may need to scroll horizontally due to deeply nested elements.
// We don't know the maximum scroll width up front, because we're windowing.
// What we can do instead, is passively measure the width of the current rows,
// and ensure that once we've grown to a new max size, we don't shrink below it.
// This improves the user experience when scrolling between wide and narrow rows.
const divRef = useRef<HTMLDivElement | null>(null);
// TODO This is a valid warning, but we're ignoring it for the time being.
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
if (divRef.current !== null) {
updateIndentationSizeVar(
divRef.current,
cachedChildWidths,
indentationSizeRef
);
}
});
// We shouldn't retain this width across different conceptual trees though,
// so when the user opens the "owners tree" view, we should discard the previous width.
const [prevOwnerID, setPrevOwnerID] = useState(ownerID);
if (ownerID !== prevOwnerID) {
setPrevOwnerID(ownerID);
}
// This style override enables the background color to fill the full visible width,
// when combined with the CSS tweaks in Element.
// A lot of options were considered; this seemed the one that requires the least code.
// See https://github.com/bvaughn/react-devtools-experimental/issues/9
return (
<div
className={styles.InnerElementType}
style={style}
ref={divRef}
{...rest}
>
<Guideline />
{children}
</div>
);
}
function Loading() {
return <div className={styles.Loading}>Loading...</div>;
}