forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReactDOMImageLoad-test.internal.js
More file actions
663 lines (582 loc) · 19.1 KB
/
ReactDOMImageLoad-test.internal.js
File metadata and controls
663 lines (582 loc) · 19.1 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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/**
* 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.
*
* @emails react-core
*/
'use strict';
let React;
let Scheduler;
// let ReactCache;
let ReactDOM;
let ReactDOMClient;
// let Suspense;
let originalCreateElement;
// let TextResource;
// let textResourceShouldFail;
let originalHTMLImageElementSrcDescriptor;
let images = [];
let onLoadSpy = null;
let actualLoadSpy = null;
let waitForAll;
let waitFor;
let assertLog;
function PhaseMarkers({children}) {
Scheduler.log('render start');
React.useLayoutEffect(() => {
Scheduler.log('last layout');
});
React.useEffect(() => {
Scheduler.log('last passive');
});
return children;
}
function last(arr) {
if (Array.isArray(arr)) {
if (arr.length) {
return arr[arr.length - 1];
}
return undefined;
}
throw new Error('last was passed something that was not an array');
}
function Text(props) {
Scheduler.log(props.text);
return props.text;
}
// function AsyncText(props) {
// const text = props.text;
// try {
// TextResource.read([props.text, props.ms]);
// Scheduler.log(text);
// return text;
// } catch (promise) {
// if (typeof promise.then === 'function') {
// Scheduler.log(`Suspend! [${text}]`);
// } else {
// Scheduler.log(`Error! [${text}]`);
// }
// throw promise;
// }
// }
function Img({src: maybeSrc, onLoad, useImageLoader, ref}) {
const src = maybeSrc || 'default';
Scheduler.log('Img ' + src);
return <img src={src} onLoad={onLoad} />;
}
function Yield() {
Scheduler.log('Yield');
Scheduler.unstable_requestPaint();
return null;
}
function loadImage(element) {
const event = new Event('load');
element.__needsDispatch = false;
element.dispatchEvent(event);
}
describe('ReactDOMImageLoad', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
Scheduler = require('scheduler');
// ReactCache = require('react-cache');
ReactDOM = require('react-dom');
ReactDOMClient = require('react-dom/client');
// Suspense = React.Suspense;
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
waitFor = InternalTestUtils.waitFor;
assertLog = InternalTestUtils.assertLog;
onLoadSpy = jest.fn(reactEvent => {
const src = reactEvent.target.getAttribute('src');
Scheduler.log('onLoadSpy [' + src + ']');
});
actualLoadSpy = jest.fn(nativeEvent => {
const src = nativeEvent.target.getAttribute('src');
Scheduler.log('actualLoadSpy [' + src + ']');
nativeEvent.__originalDispatch = false;
});
// TextResource = ReactCache.unstable_createResource(
// ([text, ms = 0]) => {
// let listeners = null;
// let status = 'pending';
// let value = null;
// return {
// then(resolve, reject) {
// switch (status) {
// case 'pending': {
// if (listeners === null) {
// listeners = [{resolve, reject}];
// setTimeout(() => {
// if (textResourceShouldFail) {
// Scheduler.log(
// `Promise rejected [${text}]`,
// );
// status = 'rejected';
// value = new Error('Failed to load: ' + text);
// listeners.forEach(listener => listener.reject(value));
// } else {
// Scheduler.log(
// `Promise resolved [${text}]`,
// );
// status = 'resolved';
// value = text;
// listeners.forEach(listener => listener.resolve(value));
// }
// }, ms);
// } else {
// listeners.push({resolve, reject});
// }
// break;
// }
// case 'resolved': {
// resolve(value);
// break;
// }
// case 'rejected': {
// reject(value);
// break;
// }
// }
// },
// };
// },
// ([text, ms]) => text,
// );
// textResourceShouldFail = false;
images = [];
originalCreateElement = document.createElement;
document.createElement = function createElement(tagName, options) {
const element = originalCreateElement.call(document, tagName, options);
if (tagName === 'img') {
element.addEventListener('load', actualLoadSpy);
images.push(element);
}
return element;
};
originalHTMLImageElementSrcDescriptor = Object.getOwnPropertyDescriptor(
HTMLImageElement.prototype,
'src',
);
Object.defineProperty(HTMLImageElement.prototype, 'src', {
get() {
return this.getAttribute('src');
},
set(value) {
Scheduler.log('load triggered');
this.__needsDispatch = true;
this.setAttribute('src', value);
},
});
});
afterEach(() => {
document.createElement = originalCreateElement;
Object.defineProperty(
HTMLImageElement.prototype,
'src',
originalHTMLImageElementSrcDescriptor,
);
});
it('captures the load event if it happens before commit phase and replays it between layout and passive effects', async function () {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
React.startTransition(() =>
root.render(
<PhaseMarkers>
<Img onLoad={onLoadSpy} />
<Yield />
<Text text={'a'} />
</PhaseMarkers>,
),
);
await waitFor(['render start', 'Img default', 'Yield']);
const img = last(images);
loadImage(img);
assertLog([
'actualLoadSpy [default]',
// no onLoadSpy since we have not completed render
]);
await waitForAll(['a', 'load triggered', 'last layout', 'last passive']);
expect(img.__needsDispatch).toBe(true);
loadImage(img);
assertLog([
'actualLoadSpy [default]', // the browser reloading of the image causes this to yield again
'onLoadSpy [default]',
]);
expect(onLoadSpy).toHaveBeenCalled();
});
it('captures the load event if it happens after commit phase and replays it', async function () {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
React.startTransition(() =>
root.render(
<PhaseMarkers>
<Img onLoad={onLoadSpy} />
</PhaseMarkers>,
),
);
await waitFor([
'render start',
'Img default',
'load triggered',
'last layout',
]);
Scheduler.unstable_requestPaint();
const img = last(images);
loadImage(img);
assertLog(['actualLoadSpy [default]', 'onLoadSpy [default]']);
await waitForAll(['last passive']);
expect(img.__needsDispatch).toBe(false);
expect(onLoadSpy).toHaveBeenCalledTimes(1);
});
it('replays the last load event when more than one fire before the end of the layout phase completes', async function () {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
function Base() {
const [src, setSrc] = React.useState('a');
return (
<PhaseMarkers>
<Img src={src} onLoad={onLoadSpy} />
<Yield />
<UpdateSrc setSrc={setSrc} />
</PhaseMarkers>
);
}
function UpdateSrc({setSrc}) {
React.useLayoutEffect(() => {
setSrc('b');
}, [setSrc]);
return null;
}
React.startTransition(() => root.render(<Base />));
await waitFor(['render start', 'Img a', 'Yield']);
const img = last(images);
loadImage(img);
assertLog(['actualLoadSpy [a]']);
await waitFor([
'load triggered',
'last layout',
// the update in layout causes a passive effects flush before a sync render
'last passive',
'render start',
'Img b',
'Yield',
// yield is ignored because we are sync rendering
'last layout',
'last passive',
]);
expect(images.length).toBe(1);
loadImage(img);
assertLog(['actualLoadSpy [b]', 'onLoadSpy [b]']);
expect(onLoadSpy).toHaveBeenCalledTimes(1);
});
it('replays load events that happen in passive phase after the passive phase.', async function () {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
root.render(
<PhaseMarkers>
<Img onLoad={onLoadSpy} />
</PhaseMarkers>,
);
await waitForAll([
'render start',
'Img default',
'load triggered',
'last layout',
'last passive',
]);
const img = last(images);
loadImage(img);
assertLog(['actualLoadSpy [default]', 'onLoadSpy [default]']);
expect(onLoadSpy).toHaveBeenCalledTimes(1);
});
it('captures and suppresses the load event if it happens before passive effects and a cascading update causes the img to be removed', async function () {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
function ChildSuppressing({children}) {
const [showChildren, update] = React.useState(true);
React.useLayoutEffect(() => {
if (showChildren) {
update(false);
}
}, [showChildren]);
return showChildren ? children : null;
}
React.startTransition(() =>
root.render(
<PhaseMarkers>
<ChildSuppressing>
<Img onLoad={onLoadSpy} />
<Yield />
<Text text={'a'} />
</ChildSuppressing>
</PhaseMarkers>,
),
);
await waitFor(['render start', 'Img default', 'Yield']);
const img = last(images);
loadImage(img);
assertLog(['actualLoadSpy [default]']);
await waitForAll(['a', 'load triggered', 'last layout', 'last passive']);
expect(img.__needsDispatch).toBe(true);
loadImage(img);
// we expect the browser to load the image again but since we are no longer rendering
// the img there will be no onLoad called
assertLog(['actualLoadSpy [default]']);
await waitForAll([]);
expect(onLoadSpy).not.toHaveBeenCalled();
});
it('captures and suppresses the load event if it happens before passive effects and a cascading update causes the img to be removed, alternate', async function () {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
function Switch({children}) {
const [shouldShow, updateShow] = React.useState(true);
return children(shouldShow, updateShow);
}
function UpdateSwitchInLayout({updateShow}) {
React.useLayoutEffect(() => {
updateShow(false);
}, []);
return null;
}
React.startTransition(() =>
root.render(
<Switch>
{(shouldShow, updateShow) => (
<PhaseMarkers>
<>
{shouldShow === true ? (
<>
<Img onLoad={onLoadSpy} />
<Yield />
<Text text={'a'} />
</>
) : null}
,
<UpdateSwitchInLayout updateShow={updateShow} />
</>
</PhaseMarkers>
)}
</Switch>,
),
);
await waitFor([
// initial render
'render start',
'Img default',
'Yield',
]);
const img = last(images);
loadImage(img);
assertLog(['actualLoadSpy [default]']);
await waitForAll([
'a',
'load triggered',
// img is present at first
'last layout',
'last passive',
// sync re-render where the img is suppressed
'render start',
'last layout',
'last passive',
]);
expect(img.__needsDispatch).toBe(true);
loadImage(img);
// we expect the browser to load the image again but since we are no longer rendering
// the img there will be no onLoad called
assertLog(['actualLoadSpy [default]']);
await waitForAll([]);
expect(onLoadSpy).not.toHaveBeenCalled();
});
// eslint-disable-next-line jest/no-commented-out-tests
// it('captures the load event if it happens in a suspended subtree and replays it between layout and passive effects on resumption', async function() {
// function SuspendingWithImage() {
// Scheduler.log('SuspendingWithImage');
// return (
// <Suspense fallback={<Text text="Loading..." />}>
// <AsyncText text="A" ms={100} />
// <PhaseMarkers>
// <Img onLoad={onLoadSpy} />
// </PhaseMarkers>
// </Suspense>
// );
// }
// const container = document.createElement('div');
// const root = ReactDOMClient.createRoot(container);
// React.startTransition(() => root.render(<SuspendingWithImage />));
// expect(Scheduler).toFlushAndYield([
// 'SuspendingWithImage',
// 'Suspend! [A]',
// 'render start',
// 'Img default',
// 'Loading...',
// ]);
// let img = last(images);
// loadImage(img);
// expect(Scheduler).toHaveYielded(['actualLoadSpy [default]']);
// expect(onLoadSpy).not.toHaveBeenCalled();
// // Flush some of the time
// jest.advanceTimersByTime(50);
// // Still nothing...
// expect(Scheduler).toFlushWithoutYielding();
// // Flush the promise completely
// jest.advanceTimersByTime(50);
// // Renders successfully
// expect(Scheduler).toHaveYielded(['Promise resolved [A]']);
// expect(Scheduler).toFlushAndYieldThrough([
// 'A',
// // img was recreated on unsuspended tree causing new load event
// 'render start',
// 'Img default',
// 'last layout',
// ]);
// expect(images.length).toBe(2);
// img = last(images);
// expect(img.__needsDispatch).toBe(true);
// loadImage(img);
// expect(Scheduler).toHaveYielded([
// 'actualLoadSpy [default]',
// 'onLoadSpy [default]',
// ]);
// expect(Scheduler).toFlushAndYield(['last passive']);
// expect(onLoadSpy).toHaveBeenCalledTimes(1);
// });
it('correctly replays the last img load even when a yield + update causes the host element to change', async function () {
let externalSetSrc = null;
let externalSetSrcAlt = null;
function Base() {
const [src, setSrc] = React.useState(null);
const [srcAlt, setSrcAlt] = React.useState(null);
externalSetSrc = setSrc;
externalSetSrcAlt = setSrcAlt;
return srcAlt || src ? <YieldingWithImage src={srcAlt || src} /> : null;
}
function YieldingWithImage({src}) {
Scheduler.log('YieldingWithImage');
React.useEffect(() => {
Scheduler.log('Committed');
});
return (
<>
<Img src={src} onLoad={onLoadSpy} />
<Yield />
<Text text={src} />
</>
);
}
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
root.render(<Base />);
await waitForAll([]);
React.startTransition(() => externalSetSrc('a'));
await waitFor(['YieldingWithImage', 'Img a', 'Yield']);
let img = last(images);
loadImage(img);
assertLog(['actualLoadSpy [a]']);
ReactDOM.flushSync(() => externalSetSrcAlt('b'));
assertLog([
'YieldingWithImage',
'Img b',
'Yield',
'b',
'load triggered',
'Committed',
]);
expect(images.length).toBe(2);
img = last(images);
expect(img.__needsDispatch).toBe(true);
loadImage(img);
assertLog(['actualLoadSpy [b]', 'onLoadSpy [b]']);
// why is there another update here?
await waitForAll(['YieldingWithImage', 'Img b', 'Yield', 'b', 'Committed']);
});
it('preserves the src property / attribute when triggering a potential new load event', async () => {
// this test covers a regression identified in https://github.com/mui/material-ui/pull/31263
// where the resetting of the src property caused the property to change from relative to fully qualified
// make sure we are not using the patched src setter
Object.defineProperty(
HTMLImageElement.prototype,
'src',
originalHTMLImageElementSrcDescriptor,
);
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
React.startTransition(() =>
root.render(
<PhaseMarkers>
<Img onLoad={onLoadSpy} />
<Yield />
<Text text={'a'} />
</PhaseMarkers>,
),
);
// render to yield to capture state of img src attribute and property before commit
await waitFor(['render start', 'Img default', 'Yield']);
const img = last(images);
const renderSrcProperty = img.src;
const renderSrcAttr = img.getAttribute('src');
// finish render and commit causing the src property to be rewritten
await waitForAll(['a', 'last layout', 'last passive']);
const commitSrcProperty = img.src;
const commitSrcAttr = img.getAttribute('src');
// ensure attribute and properties agree
expect(renderSrcProperty).toBe(commitSrcProperty);
expect(renderSrcAttr).toBe(commitSrcAttr);
});
it('captures the load event for Blob sources if it happens before commit phase', async function () {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
const blob = new Blob();
React.startTransition(() =>
root.render(
<PhaseMarkers>
<Img src={blob} onLoad={onLoadSpy} />
<Yield />
<Text text={'a'} />
</PhaseMarkers>,
),
);
await waitFor(['render start', 'Img [object Blob]', 'Yield']);
const img = last(images);
loadImage(img);
assertLog([
'actualLoadSpy [[object Blob]]',
// no onLoadSpy since we have not completed render
]);
await waitForAll(['a', 'load triggered', 'last layout', 'last passive']);
expect(img.__needsDispatch).toBe(true);
loadImage(img);
assertLog([
'actualLoadSpy [[object Blob]]', // the browser reloading of the image causes this to yield again
'onLoadSpy [[object Blob]]',
]);
expect(onLoadSpy).toHaveBeenCalled();
});
it('captures the load event for Blob sources if it happens after commit phase and replays it', async function () {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
const blob = new Blob();
React.startTransition(() =>
root.render(
<PhaseMarkers>
<Img src={blob} onLoad={onLoadSpy} />
</PhaseMarkers>,
),
);
await waitFor([
'render start',
'Img [object Blob]',
'load triggered',
'last layout',
]);
Scheduler.unstable_requestPaint();
const img = last(images);
loadImage(img);
assertLog(['actualLoadSpy [[object Blob]]', 'onLoadSpy [[object Blob]]']);
await waitForAll(['last passive']);
expect(img.__needsDispatch).toBe(false);
expect(onLoadSpy).toHaveBeenCalledTimes(1);
});
});