-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathInspectedElementSuspendedBy.js
More file actions
644 lines (620 loc) · 19.3 KB
/
InspectedElementSuspendedBy.js
File metadata and controls
644 lines (620 loc) · 19.3 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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/**
* 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 {copy} from 'clipboard-js';
import * as React from 'react';
import {useState, useTransition} from 'react';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
import KeyValue from './KeyValue';
import {serializeDataForCopy, pluralize} from '../utils';
import Store from '../../store';
import styles from './InspectedElementSharedStyles.css';
import {withPermissionsCheck} from 'react-devtools-shared/src/frontend/utils/withPermissionsCheck';
import StackTraceView from './StackTraceView';
import OwnerView from './OwnerView';
import {meta} from '../../../hydration';
import useInferredName from '../useInferredName';
import {getClassNameForEnvironment} from '../SuspenseTab/SuspenseEnvironmentColors.js';
import type {
InspectedElement,
SerializedAsyncInfo,
} from 'react-devtools-shared/src/frontend/types';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import {
UNKNOWN_SUSPENDERS_NONE,
UNKNOWN_SUSPENDERS_REASON_PRODUCTION,
UNKNOWN_SUSPENDERS_REASON_OLD_VERSION,
UNKNOWN_SUSPENDERS_REASON_THROWN_PROMISE,
} from '../../../constants';
import {ElementTypeRoot} from 'react-devtools-shared/src/frontend/types';
type RowProps = {
bridge: FrontendBridge,
element: Element,
inspectedElement: InspectedElement,
store: Store,
asyncInfo: SerializedAsyncInfo,
index: number,
minTime: number,
maxTime: number,
skipName?: boolean,
};
function getShortDescription(name: string, description: string): string {
const descMaxLength = 30 - name.length;
if (descMaxLength > 1) {
const l = description.length;
if (l > 0 && l <= descMaxLength) {
// We can fit the full description
return description;
} else if (
description.startsWith('http://') ||
description.startsWith('https://') ||
description.startsWith('/')
) {
// Looks like a URL. Let's see if we can extract something shorter.
// We don't have to do a full parse so let's try something cheaper.
let queryIdx = description.indexOf('?');
if (queryIdx === -1) {
queryIdx = description.length;
}
if (description.charCodeAt(queryIdx - 1) === 47 /* "/" */) {
// Ends with slash. Look before that.
queryIdx--;
}
const slashIdx = description.lastIndexOf('/', queryIdx - 1);
// This may now be either the file name or the host.
// Include the slash to make it more obvious what we trimmed.
return '…' + description.slice(slashIdx, queryIdx);
}
}
return '';
}
function formatBytes(bytes: number) {
if (bytes < 1_000) {
return bytes + ' bytes';
}
if (bytes < 1_000_000) {
return (bytes / 1_000).toFixed(1) + ' kB';
}
if (bytes < 1_000_000_000) {
return (bytes / 1_000_000).toFixed(1) + ' mB';
}
return (bytes / 1_000_000_000).toFixed(1) + ' gB';
}
function SuspendedByRow({
bridge,
element,
inspectedElement,
store,
asyncInfo,
index,
minTime,
maxTime,
skipName,
}: RowProps) {
const [isOpen, setIsOpen] = useState(false);
const [openIsPending, startOpenTransition] = useTransition();
const ioInfo = asyncInfo.awaited;
const name = useInferredName(asyncInfo);
const description = ioInfo.description;
const longName = description === '' ? name : name + ' (' + description + ')';
const shortDescription = getShortDescription(name, description);
const start = ioInfo.start;
const end = ioInfo.end;
const timeScale = 100 / (maxTime - minTime);
let left = (start - minTime) * timeScale;
let width = (end - start) * timeScale;
if (width < 5) {
// Use at least a 5% width to avoid showing too small indicators.
width = 5;
if (left > 95) {
left = 95;
}
}
const ioOwner = ioInfo.owner;
const asyncOwner = asyncInfo.owner;
const showIOStack = ioInfo.stack !== null && ioInfo.stack.length !== 0;
// Only show the awaited stack if the I/O started in a different owner
// than where it was awaited. If it's started by the same component it's
// probably easy enough to infer and less noise in the common case.
const canShowAwaitStack =
(asyncInfo.stack !== null && asyncInfo.stack.length > 0) ||
(asyncOwner !== null && asyncOwner.id !== inspectedElement.id);
const showAwaitStack =
canShowAwaitStack &&
(!showIOStack ||
(ioOwner === null
? asyncOwner !== null
: asyncOwner === null || ioOwner.id !== asyncOwner.id));
const value: any = ioInfo.value;
const metaName =
value !== null && typeof value === 'object' ? value[meta.name] : null;
const isFulfilled = metaName === 'fulfilled Thenable';
const isRejected = metaName === 'rejected Thenable';
return (
<div className={styles.CollapsableRow}>
<Button
className={styles.CollapsableHeader}
// TODO: May be better to leave to React's default Transition indicator.
// Though no apps implement this option at the moment.
data-pending={openIsPending}
onClick={() => {
startOpenTransition(() => {
setIsOpen(prevIsOpen => !prevIsOpen);
});
}}
// Changing the title on pending transition will not be visible since
// (Reach?) tooltips are dismissed on activation.
title={
longName +
' — ' +
(end - start).toFixed(2) +
' ms' +
(ioInfo.byteSize != null ? ' — ' + formatBytes(ioInfo.byteSize) : '')
}>
<ButtonIcon
className={styles.CollapsableHeaderIcon}
type={isOpen ? 'expanded' : 'collapsed'}
/>
<span className={styles.CollapsableHeaderTitle}>
{skipName && shortDescription !== '' ? shortDescription : name}
</span>
{skipName || shortDescription === '' ? null : (
<>
<span className={styles.CollapsableHeaderSeparator}>{' ('}</span>
<span className={styles.CollapsableHeaderTitle}>
{shortDescription}
</span>
<span className={styles.CollapsableHeaderSeparator}>{') '}</span>
</>
)}
<div className={styles.CollapsableHeaderFiller} />
<div
className={
styles.TimeBarContainer +
' ' +
getClassNameForEnvironment(ioInfo.env)
}>
<div
className={
!isRejected ? styles.TimeBarSpan : styles.TimeBarSpanErrored
}
style={{
left: left.toFixed(2) + '%',
width: width.toFixed(2) + '%',
}}
/>
</div>
</Button>
{isOpen && (
<div className={styles.CollapsableContent}>
{showIOStack && (
<StackTraceView
stack={ioInfo.stack}
environmentName={
ioOwner !== null && ioOwner.env === ioInfo.env
? null
: ioInfo.env
}
/>
)}
{ioOwner !== null &&
ioOwner.id !== inspectedElement.id &&
(showIOStack ||
!showAwaitStack ||
asyncOwner === null ||
ioOwner.id !== asyncOwner.id) ? (
<OwnerView
key={ioOwner.id}
displayName={ioOwner.displayName || 'Anonymous'}
environmentName={
ioOwner.env === inspectedElement.env &&
ioOwner.env === ioInfo.env
? null
: ioOwner.env
}
hocDisplayNames={ioOwner.hocDisplayNames}
compiledWithForget={ioOwner.compiledWithForget}
id={ioOwner.id}
isInStore={store.containsElement(ioOwner.id)}
type={ioOwner.type}
/>
) : null}
{showAwaitStack ? (
<>
<div className={styles.SmallHeader}>awaited at:</div>
{asyncInfo.stack !== null && asyncInfo.stack.length > 0 && (
<StackTraceView
stack={asyncInfo.stack}
environmentName={
asyncOwner !== null && asyncOwner.env === asyncInfo.env
? null
: asyncInfo.env
}
/>
)}
{asyncOwner !== null && asyncOwner.id !== inspectedElement.id ? (
<OwnerView
key={asyncOwner.id}
displayName={asyncOwner.displayName || 'Anonymous'}
environmentName={
asyncOwner.env === inspectedElement.env &&
asyncOwner.env === asyncInfo.env
? null
: asyncOwner.env
}
hocDisplayNames={asyncOwner.hocDisplayNames}
compiledWithForget={asyncOwner.compiledWithForget}
id={asyncOwner.id}
isInStore={store.containsElement(asyncOwner.id)}
type={asyncOwner.type}
/>
) : null}
</>
) : null}
<div className={styles.PreviewContainer}>
<KeyValue
alphaSort={true}
bridge={bridge}
canDeletePaths={false}
canEditValues={false}
canRenamePaths={false}
depth={1}
element={element}
hidden={false}
inspectedElement={inspectedElement}
name={
isFulfilled
? 'awaited value'
: isRejected
? 'rejected with'
: 'pending value'
}
path={
isFulfilled
? [index, 'awaited', 'value', 'value']
: isRejected
? [index, 'awaited', 'value', 'reason']
: [index, 'awaited', 'value']
}
pathRoot="suspendedBy"
store={store}
value={
isFulfilled ? value.value : isRejected ? value.reason : value
}
/>
</div>
</div>
)}
</div>
);
}
type Props = {
bridge: FrontendBridge,
element: Element,
inspectedElement: InspectedElement,
store: Store,
};
function withIndex(
value: SerializedAsyncInfo,
index: number,
): {
index: number,
value: SerializedAsyncInfo,
} {
return {
index,
value,
};
}
function compareTime(
a: {
index: number,
value: SerializedAsyncInfo,
},
b: {
index: number,
value: SerializedAsyncInfo,
},
): number {
const ioA = a.value.awaited;
const ioB = b.value.awaited;
if (ioA.start === ioB.start) {
return ioA.end - ioB.end;
}
return ioA.start - ioB.start;
}
type GroupProps = {
bridge: FrontendBridge,
element: Element,
inspectedElement: InspectedElement,
store: Store,
name: string,
environment: null | string,
suspendedBy: Array<{
index: number,
value: SerializedAsyncInfo,
}>,
minTime: number,
maxTime: number,
};
function SuspendedByGroup({
bridge,
element,
inspectedElement,
store,
name,
environment,
suspendedBy,
minTime,
maxTime,
}: GroupProps) {
const [isOpen, setIsOpen] = useState(false);
let start = Infinity;
let end = -Infinity;
let isRejected = false;
for (let i = 0; i < suspendedBy.length; i++) {
const asyncInfo: SerializedAsyncInfo = suspendedBy[i].value;
const ioInfo = asyncInfo.awaited;
if (ioInfo.start < start) {
start = ioInfo.start;
}
if (ioInfo.end > end) {
end = ioInfo.end;
}
const value: any = ioInfo.value;
if (
value !== null &&
typeof value === 'object' &&
value[meta.name] === 'rejected Thenable'
) {
isRejected = true;
}
}
const timeScale = 100 / (maxTime - minTime);
let left = (start - minTime) * timeScale;
let width = (end - start) * timeScale;
if (width < 5) {
// Use at least a 5% width to avoid showing too small indicators.
width = 5;
if (left > 95) {
left = 95;
}
}
const pluralizedName = pluralize(name);
return (
<div className={styles.CollapsableRow}>
<Button
className={styles.CollapsableHeader}
onClick={() => {
setIsOpen(prevIsOpen => !prevIsOpen);
}}
title={pluralizedName}>
<ButtonIcon
className={styles.CollapsableHeaderIcon}
type={isOpen ? 'expanded' : 'collapsed'}
/>
<span className={styles.CollapsableHeaderTitle}>{pluralizedName}</span>
<div className={styles.CollapsableHeaderFiller} />
{isOpen ? null : (
<div
className={
styles.TimeBarContainer +
' ' +
getClassNameForEnvironment(environment)
}>
<div
className={
!isRejected ? styles.TimeBarSpan : styles.TimeBarSpanErrored
}
style={{
left: left.toFixed(2) + '%',
width: width.toFixed(2) + '%',
}}
/>
</div>
)}
</Button>
{isOpen &&
suspendedBy.map(({value, index}) => (
<SuspendedByRow
key={index}
index={index}
asyncInfo={value}
bridge={bridge}
element={element}
inspectedElement={inspectedElement}
store={store}
minTime={minTime}
maxTime={maxTime}
skipName={true}
/>
))}
</div>
);
}
export default function InspectedElementSuspendedBy({
bridge,
element,
inspectedElement,
store,
}: Props): React.Node {
const {suspendedBy, suspendedByRange} = inspectedElement;
// Skip the section if nothing suspended this component.
if (
(suspendedBy == null || suspendedBy.length === 0) &&
inspectedElement.unknownSuspenders === UNKNOWN_SUSPENDERS_NONE
) {
if (inspectedElement.isSuspended) {
// If we're still suspended, show a place holder until the data loads.
// We don't know what we're suspended by until it has loaded.
return (
<div>
<div className={styles.HeaderRow}>
<div className={styles.Header}>suspended...</div>
</div>
</div>
);
}
// For roots, show an empty state since there's nothing else to show for
// these elements.
// This can happen for older versions of React without Suspense, older versions
// of React with less sources for Suspense, or simple UIs that don't have any suspenders.
if (inspectedElement.type === ElementTypeRoot) {
return (
<div>
<div className={styles.HeaderRow}>
<div className={`${styles.Header} ${styles.Empty}`}>
Nothing suspended the initial paint.
</div>
</div>
</div>
);
}
}
const handleCopy = withPermissionsCheck(
{permissions: ['clipboardWrite']},
() => copy(serializeDataForCopy(suspendedBy)),
);
let minTime = Infinity;
let maxTime = -Infinity;
if (suspendedByRange !== null) {
// The range of the whole suspense boundary.
minTime = suspendedByRange[0];
maxTime = suspendedByRange[1];
}
for (let i = 0; i < suspendedBy.length; i++) {
const asyncInfo: SerializedAsyncInfo = suspendedBy[i];
if (asyncInfo.awaited.start < minTime) {
minTime = asyncInfo.awaited.start;
}
if (asyncInfo.awaited.end > maxTime) {
maxTime = asyncInfo.awaited.end;
}
}
if (maxTime - minTime < 25) {
// Stretch the time span a bit to ensure that we don't show
// large bars that represent very small timespans.
minTime = maxTime - 25;
}
const sortedSuspendedBy =
suspendedBy === null ? [] : suspendedBy.map(withIndex);
sortedSuspendedBy.sort(compareTime);
// Organize into groups of consecutive entries with the same name.
const groups = [];
let currentGroup = null;
let currentGroupName = null;
let currentGroupEnv = null;
for (let i = 0; i < sortedSuspendedBy.length; i++) {
const entry = sortedSuspendedBy[i];
const name = entry.value.awaited.name;
const env = entry.value.awaited.env;
if (
currentGroupName !== name ||
currentGroupEnv !== env ||
!name ||
name === 'Promise' ||
currentGroup === null
) {
// Create a new group.
currentGroupName = name;
currentGroupEnv = env;
currentGroup = [];
groups.push(currentGroup);
}
currentGroup.push(entry);
}
let unknownSuspenders = null;
switch (inspectedElement.unknownSuspenders) {
case UNKNOWN_SUSPENDERS_REASON_PRODUCTION:
unknownSuspenders = (
<div className={styles.InfoRow}>
Something suspended but we don't know the exact reason in production
builds of React. Test this in development mode to see exactly what
might suspend.
</div>
);
break;
case UNKNOWN_SUSPENDERS_REASON_OLD_VERSION:
unknownSuspenders = (
<div className={styles.InfoRow}>
Something suspended but we don't track all the necessary information
in older versions of React. Upgrade to the latest version of React to
see exactly what might suspend.
</div>
);
break;
case UNKNOWN_SUSPENDERS_REASON_THROWN_PROMISE:
unknownSuspenders = (
<div className={styles.InfoRow}>
Something threw a Promise to suspend this boundary. It's likely an
outdated version of a library that doesn't yet fully take advantage of
use(). Upgrade your data fetching library to see exactly what might
suspend.
</div>
);
break;
}
if (groups.length === 0) {
return null;
}
return (
<div>
<div className={styles.HeaderRow}>
<div className={styles.Header}>suspended by</div>
<Button onClick={handleCopy} title="Copy to clipboard">
<ButtonIcon type="copy" />
</Button>
</div>
{groups.length === 1
? // If it's only one type of suspender we can flatten it.
groups[0].map(entry => (
<SuspendedByRow
key={entry.index}
index={entry.index}
asyncInfo={entry.value}
bridge={bridge}
element={element}
inspectedElement={inspectedElement}
store={store}
minTime={minTime}
maxTime={maxTime}
/>
))
: groups.map((entries, index) =>
entries.length === 1 ? (
<SuspendedByRow
key={entries[0].index}
index={entries[0].index}
asyncInfo={entries[0].value}
bridge={bridge}
element={element}
inspectedElement={inspectedElement}
store={store}
minTime={minTime}
maxTime={maxTime}
/>
) : (
<SuspendedByGroup
key={entries[0].index}
name={entries[0].value.awaited.name}
environment={entries[0].value.awaited.env}
suspendedBy={entries}
bridge={bridge}
element={element}
inspectedElement={inspectedElement}
store={store}
minTime={minTime}
maxTime={maxTime}
/>
),
)}
{unknownSuspenders}
</div>
);
}