forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReactFiberHydrationDiffs.js
656 lines (608 loc) · 19.1 KB
/
ReactFiberHydrationDiffs.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
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
645
646
647
648
649
650
651
652
653
654
655
656
/**
* 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 type {Fiber} from './ReactInternalTypes';
import {
HostComponent,
HostHoistable,
HostSingleton,
LazyComponent,
ActivityComponent,
SuspenseComponent,
SuspenseListComponent,
FunctionComponent,
ForwardRef,
SimpleMemoComponent,
ClassComponent,
HostText,
} from './ReactWorkTags';
import {enableSrcObject} from 'shared/ReactFeatureFlags';
import {REACT_ELEMENT_TYPE} from 'shared/ReactSymbols';
import assign from 'shared/assign';
import getComponentNameFromType from 'shared/getComponentNameFromType';
import isArray from 'shared/isArray';
export type HydrationDiffNode = {
fiber: Fiber,
children: Array<HydrationDiffNode>,
serverProps: void | null | $ReadOnly<{[propName: string]: mixed}> | string, // null means no matching server node
serverTail: Array<
| $ReadOnly<{type: string, props: $ReadOnly<{[propName: string]: mixed}>}>
| string,
>,
distanceFromLeaf: number,
};
const maxRowLength = 120;
const idealDepth = 15;
function findNotableNode(
node: HydrationDiffNode,
indent: number,
): HydrationDiffNode {
if (
node.serverProps === undefined &&
node.serverTail.length === 0 &&
node.children.length === 1 &&
node.distanceFromLeaf > 3 &&
node.distanceFromLeaf > idealDepth - indent
) {
// This is not an interesting node for contextual purposes so we can skip it.
const child = node.children[0];
return findNotableNode(child, indent);
}
return node;
}
function indentation(indent: number): string {
return ' ' + ' '.repeat(indent);
}
function added(indent: number): string {
return '+ ' + ' '.repeat(indent);
}
function removed(indent: number): string {
return '- ' + ' '.repeat(indent);
}
function describeFiberType(fiber: Fiber): null | string {
switch (fiber.tag) {
case HostHoistable:
case HostSingleton:
case HostComponent:
return fiber.type;
case LazyComponent:
return 'Lazy';
case ActivityComponent:
return 'Activity';
case SuspenseComponent:
return 'Suspense';
case SuspenseListComponent:
return 'SuspenseList';
case FunctionComponent:
case SimpleMemoComponent:
const fn = fiber.type;
return fn.displayName || fn.name || null;
case ForwardRef:
const render = fiber.type.render;
return render.displayName || render.name || null;
case ClassComponent:
const ctr = fiber.type;
return ctr.displayName || ctr.name || null;
default:
// Skip
return null;
}
}
const needsEscaping = /["'&<>\n\t]|^\s|\s$/;
function describeTextNode(content: string, maxLength: number): string {
if (needsEscaping.test(content)) {
const encoded = JSON.stringify(content);
if (encoded.length > maxLength - 2) {
if (maxLength < 8) {
return '{"..."}';
}
return '{' + encoded.slice(0, maxLength - 7) + '..."}';
}
return '{' + encoded + '}';
} else {
if (content.length > maxLength) {
if (maxLength < 5) {
return '{"..."}';
}
return content.slice(0, maxLength - 3) + '...';
}
return content;
}
}
function describeTextDiff(
clientText: string,
serverProps: mixed,
indent: number,
): string {
const maxLength = maxRowLength - indent * 2;
if (serverProps === null) {
return added(indent) + describeTextNode(clientText, maxLength) + '\n';
} else if (typeof serverProps === 'string') {
let serverText: string = serverProps;
let firstDiff = 0;
for (
;
firstDiff < serverText.length && firstDiff < clientText.length;
firstDiff++
) {
if (
serverText.charCodeAt(firstDiff) !== clientText.charCodeAt(firstDiff)
) {
break;
}
}
if (firstDiff > maxLength - 8 && firstDiff > 10) {
// The first difference between the two strings would be cut off, so cut off in
// the beginning instead.
clientText = '...' + clientText.slice(firstDiff - 8);
serverText = '...' + serverText.slice(firstDiff - 8);
}
return (
added(indent) +
describeTextNode(clientText, maxLength) +
'\n' +
removed(indent) +
describeTextNode(serverText, maxLength) +
'\n'
);
} else {
return indentation(indent) + describeTextNode(clientText, maxLength) + '\n';
}
}
function objectName(object: mixed): string {
// $FlowFixMe[method-unbinding]
const name = Object.prototype.toString.call(object);
return name.replace(/^\[object (.*)\]$/, function (m, p0) {
return p0;
});
}
function describeValue(value: mixed, maxLength: number): string {
switch (typeof value) {
case 'string': {
const encoded = JSON.stringify(value);
if (encoded.length > maxLength) {
if (maxLength < 5) {
return '"..."';
}
return encoded.slice(0, maxLength - 4) + '..."';
}
return encoded;
}
case 'object': {
if (value === null) {
return 'null';
}
if (isArray(value)) {
return '[...]';
}
if ((value: any).$$typeof === REACT_ELEMENT_TYPE) {
const type = getComponentNameFromType((value: any).type);
return type ? '<' + type + '>' : '<...>';
}
const name = objectName(value);
if (name === 'Object') {
let properties = '';
maxLength -= 2;
for (let propName in value) {
if (!value.hasOwnProperty(propName)) {
continue;
}
const jsonPropName = JSON.stringify(propName);
if (jsonPropName !== '"' + propName + '"') {
propName = jsonPropName;
}
maxLength -= propName.length - 2;
const propValue = describeValue(
value[propName],
maxLength < 15 ? maxLength : 15,
);
maxLength -= propValue.length;
if (maxLength < 0) {
properties += properties === '' ? '...' : ', ...';
break;
}
properties +=
(properties === '' ? '' : ',') + propName + ':' + propValue;
}
return '{' + properties + '}';
} else if (enableSrcObject && (name === 'Blob' || name === 'File')) {
return name + ':' + (value: any).type;
}
return name;
}
case 'function': {
const name = (value: any).displayName || value.name;
return name ? 'function ' + name : 'function';
}
default:
// eslint-disable-next-line react-internal/safe-string-coercion
return String(value);
}
}
function describePropValue(value: mixed, maxLength: number): string {
if (typeof value === 'string' && !needsEscaping.test(value)) {
if (value.length > maxLength - 2) {
if (maxLength < 5) {
return '"..."';
}
return '"' + value.slice(0, maxLength - 5) + '..."';
}
return '"' + value + '"';
}
return '{' + describeValue(value, maxLength - 2) + '}';
}
function describeCollapsedElement(
type: string,
props: {[propName: string]: mixed},
indent: number,
): string {
// This function tries to fit the props into a single line for non-essential elements.
// We also ignore children because we're not going deeper.
let maxLength = maxRowLength - indent * 2 - type.length - 2;
let content = '';
for (const propName in props) {
if (!props.hasOwnProperty(propName)) {
continue;
}
if (propName === 'children') {
// Ignored.
continue;
}
const propValue = describePropValue(props[propName], 15);
maxLength -= propName.length + propValue.length + 2;
if (maxLength < 0) {
content += ' ...';
break;
}
content += ' ' + propName + '=' + propValue;
}
return indentation(indent) + '<' + type + content + '>\n';
}
function describeExpandedElement(
type: string,
props: {+[propName: string]: mixed},
rowPrefix: string,
): string {
// This function tries to fit the props into a single line for non-essential elements.
// We also ignore children because we're not going deeper.
let remainingRowLength = maxRowLength - rowPrefix.length - type.length;
// We add the properties to a set so we can choose later whether we'll put it on one
// line or multiple lines.
const properties = [];
for (const propName in props) {
if (!props.hasOwnProperty(propName)) {
continue;
}
if (propName === 'children') {
// Ignored.
continue;
}
const maxLength = maxRowLength - rowPrefix.length - propName.length - 1;
const propValue = describePropValue(props[propName], maxLength);
remainingRowLength -= propName.length + propValue.length + 2;
properties.push(propName + '=' + propValue);
}
if (properties.length === 0) {
return rowPrefix + '<' + type + '>\n';
} else if (remainingRowLength > 0) {
// We can fit all on one row.
return rowPrefix + '<' + type + ' ' + properties.join(' ') + '>\n';
} else {
// Split into one row per property:
return (
rowPrefix +
'<' +
type +
'\n' +
rowPrefix +
' ' +
properties.join('\n' + rowPrefix + ' ') +
'\n' +
rowPrefix +
'>\n'
);
}
}
function describePropertiesDiff(
clientObject: {+[propName: string]: mixed},
serverObject: {+[propName: string]: mixed},
indent: number,
): string {
let properties = '';
const remainingServerProperties = assign({}, serverObject);
for (const propName in clientObject) {
if (!clientObject.hasOwnProperty(propName)) {
continue;
}
delete remainingServerProperties[propName];
const maxLength = maxRowLength - indent * 2 - propName.length - 2;
const clientValue = clientObject[propName];
const clientPropValue = describeValue(clientValue, maxLength);
if (serverObject.hasOwnProperty(propName)) {
const serverValue = serverObject[propName];
const serverPropValue = describeValue(serverValue, maxLength);
properties += added(indent) + propName + ': ' + clientPropValue + '\n';
properties += removed(indent) + propName + ': ' + serverPropValue + '\n';
} else {
properties += added(indent) + propName + ': ' + clientPropValue + '\n';
}
}
for (const propName in remainingServerProperties) {
if (!remainingServerProperties.hasOwnProperty(propName)) {
continue;
}
const maxLength = maxRowLength - indent * 2 - propName.length - 2;
const serverValue = remainingServerProperties[propName];
const serverPropValue = describeValue(serverValue, maxLength);
properties += removed(indent) + propName + ': ' + serverPropValue + '\n';
}
return properties;
}
function describeElementDiff(
type: string,
clientProps: {+[propName: string]: mixed},
serverProps: {+[propName: string]: mixed},
indent: number,
): string {
let content = '';
// Maps any previously unmatched lower case server prop name to its full prop name
const serverPropNames: Map<string, string> = new Map();
for (const propName in serverProps) {
if (!serverProps.hasOwnProperty(propName)) {
continue;
}
serverPropNames.set(propName.toLowerCase(), propName);
}
if (serverPropNames.size === 1 && serverPropNames.has('children')) {
content += describeExpandedElement(type, clientProps, indentation(indent));
} else {
for (const propName in clientProps) {
if (!clientProps.hasOwnProperty(propName)) {
continue;
}
if (propName === 'children') {
// Handled below.
continue;
}
const maxLength = maxRowLength - (indent + 1) * 2 - propName.length - 1;
const serverPropName = serverPropNames.get(propName.toLowerCase());
if (serverPropName !== undefined) {
serverPropNames.delete(propName.toLowerCase());
// There's a diff here.
const clientValue = clientProps[propName];
const serverValue = serverProps[serverPropName];
const clientPropValue = describePropValue(clientValue, maxLength);
const serverPropValue = describePropValue(serverValue, maxLength);
if (
typeof clientValue === 'object' &&
clientValue !== null &&
typeof serverValue === 'object' &&
serverValue !== null &&
objectName(clientValue) === 'Object' &&
objectName(serverValue) === 'Object' &&
// Only do the diff if the object has a lot of keys or was shortened.
(Object.keys(clientValue).length > 2 ||
Object.keys(serverValue).length > 2 ||
clientPropValue.indexOf('...') > -1 ||
serverPropValue.indexOf('...') > -1)
) {
// We're comparing two plain objects. We can diff the nested objects instead.
content +=
indentation(indent + 1) +
propName +
'={{\n' +
describePropertiesDiff(clientValue, serverValue, indent + 2) +
indentation(indent + 1) +
'}}\n';
} else {
content +=
added(indent + 1) + propName + '=' + clientPropValue + '\n';
content +=
removed(indent + 1) + propName + '=' + serverPropValue + '\n';
}
} else {
// Considered equal.
content +=
indentation(indent + 1) +
propName +
'=' +
describePropValue(clientProps[propName], maxLength) +
'\n';
}
}
serverPropNames.forEach(propName => {
if (propName === 'children') {
// Handled below.
return;
}
const maxLength = maxRowLength - (indent + 1) * 2 - propName.length - 1;
content +=
removed(indent + 1) +
propName +
'=' +
describePropValue(serverProps[propName], maxLength) +
'\n';
});
if (content === '') {
// No properties
content = indentation(indent) + '<' + type + '>\n';
} else {
// Had properties
content =
indentation(indent) +
'<' +
type +
'\n' +
content +
indentation(indent) +
'>\n';
}
}
const serverChildren = serverProps.children;
const clientChildren = clientProps.children;
if (
typeof serverChildren === 'string' ||
typeof serverChildren === 'number' ||
typeof serverChildren === 'bigint'
) {
// There's a diff of the children.
// $FlowFixMe[unsafe-addition]
const serverText = '' + serverChildren;
let clientText = '';
if (
typeof clientChildren === 'string' ||
typeof clientChildren === 'number' ||
typeof clientChildren === 'bigint'
) {
// $FlowFixMe[unsafe-addition]
clientText = '' + clientChildren;
}
content += describeTextDiff(clientText, serverText, indent + 1);
} else if (
typeof clientChildren === 'string' ||
typeof clientChildren === 'number' ||
typeof clientChildren === 'bigint'
) {
if (serverChildren == null) {
// This is a new string child.
// $FlowFixMe[unsafe-addition]
content += describeTextDiff('' + clientChildren, null, indent + 1);
} else {
// The client has children but it's not considered a difference from the server.
// $FlowFixMe[unsafe-addition]
content += describeTextDiff('' + clientChildren, undefined, indent + 1);
}
}
return content;
}
function describeSiblingFiber(fiber: Fiber, indent: number): string {
const type = describeFiberType(fiber);
if (type === null) {
// Skip this type of fiber. We currently treat this as a fragment
// so it's just part of the parent's children.
let flatContent = '';
let childFiber = fiber.child;
while (childFiber) {
flatContent += describeSiblingFiber(childFiber, indent);
childFiber = childFiber.sibling;
}
return flatContent;
}
return indentation(indent) + '<' + type + '>' + '\n';
}
function describeNode(node: HydrationDiffNode, indent: number): string {
const skipToNode = findNotableNode(node, indent);
if (
skipToNode !== node &&
(node.children.length !== 1 || node.children[0] !== skipToNode)
) {
return indentation(indent) + '...\n' + describeNode(skipToNode, indent + 1);
}
// Prefix with any server components for context
let parentContent = '';
const debugInfo = node.fiber._debugInfo;
if (debugInfo) {
for (let i = 0; i < debugInfo.length; i++) {
const serverComponentName = debugInfo[i].name;
if (typeof serverComponentName === 'string') {
parentContent +=
indentation(indent) + '<' + serverComponentName + '>' + '\n';
indent++;
}
}
}
// Self
let selfContent = '';
// We use the pending props since we might be generating a diff before the complete phase
// when something throws.
const clientProps = node.fiber.pendingProps;
if (node.fiber.tag === HostText) {
// Text Node
selfContent = describeTextDiff(clientProps, node.serverProps, indent);
indent++;
} else {
const type = describeFiberType(node.fiber);
if (type !== null) {
// Element Node
if (node.serverProps === undefined) {
// Just a reference node for context.
selfContent = describeCollapsedElement(type, clientProps, indent);
indent++;
} else if (node.serverProps === null) {
selfContent = describeExpandedElement(type, clientProps, added(indent));
indent++;
} else if (typeof node.serverProps === 'string') {
if (__DEV__) {
console.error(
'Should not have matched a non HostText fiber to a Text node. This is a bug in React.',
);
}
} else {
selfContent = describeElementDiff(
type,
clientProps,
node.serverProps,
indent,
);
indent++;
}
}
}
// Compute children
let childContent = '';
let childFiber = node.fiber.child;
let diffIdx = 0;
while (childFiber && diffIdx < node.children.length) {
const childNode = node.children[diffIdx];
if (childNode.fiber === childFiber) {
// This was a match in the diff.
childContent += describeNode(childNode, indent);
diffIdx++;
} else {
// This is an unrelated previous sibling.
childContent += describeSiblingFiber(childFiber, indent);
}
childFiber = childFiber.sibling;
}
if (childFiber && node.children.length > 0) {
// If we had any further siblings after the last mismatch, we can't be sure if it's
// actually a valid match since it might not have found a match. So we exclude next
// siblings to avoid confusion.
childContent += indentation(indent) + '...' + '\n';
}
// Deleted tail nodes
const serverTail = node.serverTail;
if (node.serverProps === null) {
indent--;
}
for (let i = 0; i < serverTail.length; i++) {
const tailNode = serverTail[i];
if (typeof tailNode === 'string') {
// Removed text node
childContent +=
removed(indent) +
describeTextNode(tailNode, maxRowLength - indent * 2) +
'\n';
} else {
// Removed element
childContent += describeExpandedElement(
tailNode.type,
tailNode.props,
removed(indent),
);
}
}
return parentContent + selfContent + childContent;
}
export function describeDiff(rootNode: HydrationDiffNode): string {
try {
return '\n\n' + describeNode(rootNode, 0);
} catch (x) {
return '';
}
}