-
Notifications
You must be signed in to change notification settings - Fork 45.5k
/
ReactDOMUseId-test.js
635 lines (594 loc) · 15.4 KB
/
ReactDOMUseId-test.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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
*/
let React;
let ReactDOMClient;
let Scheduler;
let clientAct;
let ReactDOMFizzServer;
let Stream;
let Suspense;
let useId;
let useState;
let writable;
let container;
let buffer = '';
let hasErrored = false;
let fatalError = undefined;
describe('useId', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOMClient = require('react-dom/client');
Scheduler = require('scheduler');
clientAct = require('jest-react').act;
ReactDOMFizzServer = require('react-dom/server');
Stream = require('stream');
Suspense = React.Suspense;
useId = React.useId;
useState = React.useState;
container = document.createElement('div');
container.setAttribute('id', 'container');
document.body.appendChild(container);
buffer = '';
hasErrored = false;
writable = new Stream.PassThrough();
writable.setEncoding('utf8');
writable.on('data', chunk => {
buffer += chunk;
});
writable.on('error', error => {
hasErrored = true;
fatalError = error;
});
});
afterEach(() => {
container?.remove();
container = null;
});
async function serverAct(callback) {
await callback();
// Await one turn around the event loop.
// This assumes that we'll flush everything we have so far.
await new Promise(resolve => {
setImmediate(resolve);
});
if (hasErrored) {
throw fatalError;
}
// JSDOM doesn't support stream HTML parser so we need to give it a proper fragment.
// We also want to execute any scripts that are embedded.
// We assume that we have now received a proper fragment of HTML.
const bufferedContent = buffer;
buffer = '';
const fakeBody = document.createElement('body');
fakeBody.innerHTML = bufferedContent;
while (fakeBody.firstChild) {
const node = fakeBody.firstChild;
if (node.nodeName === 'SCRIPT') {
const script = document.createElement('script');
script.textContent = node.textContent;
fakeBody.removeChild(node);
container.appendChild(script);
} else {
container.appendChild(node);
}
}
}
function normalizeTreeIdForTesting(id) {
const result = id.match(/:(R|r)([a-z0-9]*)(H([0-9]*))?:/);
if (result === undefined) {
throw new Error('Invalid id format');
}
const [, serverClientPrefix, base32, hookIndex] = result;
if (serverClientPrefix.endsWith('r')) {
// Client ids aren't stable. For testing purposes, strip out the counter.
return (
'CLIENT_GENERATED_ID' +
(hookIndex !== undefined ? ` (${hookIndex})` : '')
);
}
// Formats the tree id as a binary sequence, so it's easier to visualize
// the structure.
return (
parseInt(base32, 32).toString(2) +
(hookIndex !== undefined ? ` (${hookIndex})` : '')
);
}
function DivWithId({children}) {
const id = normalizeTreeIdForTesting(useId());
return <div id={id}>{children}</div>;
}
test('basic example', async () => {
function App() {
return (
<div>
<div>
<DivWithId />
<DivWithId />
</div>
<DivWithId />
</div>
);
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
await clientAct(async () => {
ReactDOMClient.hydrateRoot(container, <App />);
});
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<div>
<div>
<div
id="101"
/>
<div
id="1001"
/>
</div>
<div
id="10"
/>
</div>
</div>
`);
});
test('indirections', async () => {
function App() {
// There are no forks in this tree, but the parent and the child should
// have different ids.
return (
<DivWithId>
<div>
<div>
<div>
<DivWithId />
</div>
</div>
</div>
</DivWithId>
);
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
await clientAct(async () => {
ReactDOMClient.hydrateRoot(container, <App />);
});
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<div
id="0"
>
<div>
<div>
<div>
<div
id="1"
/>
</div>
</div>
</div>
</div>
</div>
`);
});
test('StrictMode double rendering', async () => {
const {StrictMode} = React;
function App() {
return (
<StrictMode>
<DivWithId />
</StrictMode>
);
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
await clientAct(async () => {
ReactDOMClient.hydrateRoot(container, <App />);
});
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<div
id="0"
/>
</div>
`);
});
test('empty (null) children', async () => {
// We don't treat empty children different from non-empty ones, which means
// they get allocated a slot when generating ids. There's no inherent reason
// to do this; Fiber happens to allocate a fiber for null children that
// appear in a list, which is not ideal for performance. For the purposes
// of id generation, though, what matters is that Fizz and Fiber
// are consistent.
function App() {
return (
<>
{null}
<DivWithId />
{null}
<DivWithId />
</>
);
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
await clientAct(async () => {
ReactDOMClient.hydrateRoot(container, <App />);
});
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<div
id="10"
/>
<div
id="100"
/>
</div>
`);
});
test('large ids', async () => {
// The component in this test outputs a recursive tree of nodes with ids,
// where the underlying binary representation is an alternating series of 1s
// and 0s. In other words, they are all of the form 101010101.
//
// Because we use base 32 encoding, the resulting id should consist of
// alternating 'a' (01010) and 'l' (10101) characters, except for the the
// 'R:' prefix, and the first character after that, which may not correspond
// to a complete set of 5 bits.
//
// Example: :Rclalalalalalalala...:
//
// We can use this pattern to test large ids that exceed the bitwise
// safe range (32 bits). The algorithm should theoretically support ids
// of any size.
function Child({children}) {
const id = useId();
return <div id={id}>{children}</div>;
}
function App() {
let tree = <Child />;
for (let i = 0; i < 50; i++) {
tree = (
<>
<Child />
{tree}
</>
);
}
return tree;
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
await clientAct(async () => {
ReactDOMClient.hydrateRoot(container, <App />);
});
const divs = container.querySelectorAll('div');
// Confirm that every id matches the expected pattern
for (let i = 0; i < divs.length; i++) {
// Example: :Rclalalalalalalala...:
expect(divs[i].id).toMatch(/^:R.(((al)*a?)((la)*l?))*:$/);
}
});
test('multiple ids in a single component', async () => {
function App() {
const id1 = useId();
const id2 = useId();
const id3 = useId();
return `${id1}, ${id2}, ${id3}`;
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
await clientAct(async () => {
ReactDOMClient.hydrateRoot(container, <App />);
});
// We append a suffix to the end of the id to distinguish them
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
:R0:, :R0H1:, :R0H2:
<!-- -->
</div>
`);
});
test('local render phase updates', async () => {
function App({swap}) {
const [count, setCount] = useState(0);
if (count < 3) {
setCount(count + 1);
}
return useId();
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
await clientAct(async () => {
ReactDOMClient.hydrateRoot(container, <App />);
});
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
:R0:
<!-- -->
</div>
`);
});
test('basic incremental hydration', async () => {
function App() {
return (
<div>
<Suspense fallback="Loading...">
<DivWithId label="A" />
<DivWithId label="B" />
</Suspense>
<DivWithId label="C" />
</div>
);
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
await clientAct(async () => {
ReactDOMClient.hydrateRoot(container, <App />);
});
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<div>
<!--$-->
<div
id="101"
/>
<div
id="1001"
/>
<!--/$-->
<div
id="10"
/>
</div>
</div>
`);
});
test('inserting/deleting siblings outside a dehydrated Suspense boundary', async () => {
const span = React.createRef(null);
function App({swap}) {
// Note: Using a dynamic array so these are treated as insertions and
// deletions instead of updates, because Fiber currently allocates a node
// even for empty children.
const children = [
<DivWithId key="A" />,
swap ? <DivWithId key="C" /> : <DivWithId key="B" />,
<DivWithId key="D" />,
];
return (
<>
{children}
<Suspense key="boundary" fallback="Loading...">
<DivWithId />
<span ref={span} />
</Suspense>
</>
);
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
const dehydratedSpan = container.getElementsByTagName('span')[0];
await clientAct(async () => {
const root = ReactDOMClient.hydrateRoot(container, <App />);
expect(Scheduler).toFlushUntilNextPaint([]);
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<div
id="101"
/>
<div
id="1001"
/>
<div
id="1101"
/>
<!--$-->
<div
id="110"
/>
<span />
<!--/$-->
</div>
`);
// The inner boundary hasn't hydrated yet
expect(span.current).toBe(null);
// Swap B for C
root.render(<App swap={true} />);
});
// The swap should not have caused a mismatch.
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<div
id="101"
/>
<div
id="CLIENT_GENERATED_ID"
/>
<div
id="1101"
/>
<!--$-->
<div
id="110"
/>
<span />
<!--/$-->
</div>
`);
// Should have hydrated successfully
expect(span.current).toBe(dehydratedSpan);
});
test('inserting/deleting siblings inside a dehydrated Suspense boundary', async () => {
const span = React.createRef(null);
function App({swap}) {
// Note: Using a dynamic array so these are treated as insertions and
// deletions instead of updates, because Fiber currently allocates a node
// even for empty children.
const children = [
<DivWithId key="A" />,
swap ? <DivWithId key="C" /> : <DivWithId key="B" />,
<DivWithId key="D" />,
];
return (
<Suspense key="boundary" fallback="Loading...">
{children}
<span ref={span} />
</Suspense>
);
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
const dehydratedSpan = container.getElementsByTagName('span')[0];
await clientAct(async () => {
const root = ReactDOMClient.hydrateRoot(container, <App />);
expect(Scheduler).toFlushUntilNextPaint([]);
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<!--$-->
<div
id="101"
/>
<div
id="1001"
/>
<div
id="1101"
/>
<span />
<!--/$-->
</div>
`);
// The inner boundary hasn't hydrated yet
expect(span.current).toBe(null);
// Swap B for C
root.render(<App swap={true} />);
});
// The swap should not have caused a mismatch.
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<!--$-->
<div
id="101"
/>
<div
id="CLIENT_GENERATED_ID"
/>
<div
id="1101"
/>
<span />
<!--/$-->
</div>
`);
// Should have hydrated successfully
expect(span.current).toBe(dehydratedSpan);
});
test('identifierPrefix option', async () => {
function Child() {
const id = useId();
return <div>{id}</div>;
}
function App({showMore}) {
return (
<>
<Child />
<Child />
{showMore && <Child />}
</>
);
}
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />, {
identifierPrefix: 'custom-prefix-',
});
pipe(writable);
});
let root;
await clientAct(async () => {
root = ReactDOMClient.hydrateRoot(container, <App />, {
identifierPrefix: 'custom-prefix-',
});
});
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<div>
:custom-prefix-R1:
</div>
<div>
:custom-prefix-R2:
</div>
</div>
`);
// Mount a new, client-only id
await clientAct(async () => {
root.render(<App showMore={true} />);
});
expect(container).toMatchInlineSnapshot(`
<div
id="container"
>
<div>
:custom-prefix-R1:
</div>
<div>
:custom-prefix-R2:
</div>
<div>
:custom-prefix-r0:
</div>
</div>
`);
});
});