forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReactFiberScheduler.js
1583 lines (1428 loc) · 51.1 KB
/
ReactFiberScheduler.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ReactFiberScheduler
* @flow
*/
'use strict';
import type {Fiber} from 'ReactFiber';
import type {FiberRoot} from 'ReactFiberRoot';
import type {HostConfig, Deadline} from 'ReactFiberReconciler';
import type {PriorityLevel} from 'ReactPriorityLevel';
import type {HydrationContext} from 'ReactFiberHydrationContext';
export type CapturedError = {
componentName: ?string,
componentStack: string,
error: mixed,
errorBoundary: ?Object,
errorBoundaryFound: boolean,
errorBoundaryName: string | null,
willRetry: boolean,
};
export type HandleErrorInfo = {
componentStack: string,
};
var {popContextProvider} = require('ReactFiberContext');
const {reset} = require('ReactFiberStack');
var {
getStackAddendumByWorkInProgressFiber,
} = require('ReactFiberComponentTreeHook');
var {logCapturedError} = require('ReactFiberErrorLogger');
var {
invokeGuardedCallback,
hasCaughtError,
clearCaughtError,
} = require('ReactErrorUtils');
var ReactFiberBeginWork = require('ReactFiberBeginWork');
var ReactFiberCompleteWork = require('ReactFiberCompleteWork');
var ReactFiberCommitWork = require('ReactFiberCommitWork');
var ReactFiberHostContext = require('ReactFiberHostContext');
var ReactFiberHydrationContext = require('ReactFiberHydrationContext');
var {ReactCurrentOwner} = require('ReactGlobalSharedState');
var getComponentName = require('getComponentName');
var {createWorkInProgress, largerPriority} = require('ReactFiber');
var {onCommitRoot} = require('ReactFiberDevToolsHook');
var {
NoWork,
SynchronousPriority,
TaskPriority,
HighPriority,
LowPriority,
OffscreenPriority,
} = require('ReactPriorityLevel');
var {AsyncUpdates} = require('ReactTypeOfInternalContext');
var {
PerformedWork,
Placement,
Update,
PlacementAndUpdate,
Deletion,
ContentReset,
Callback,
Err,
Ref,
} = require('ReactTypeOfSideEffect');
var {
HostRoot,
HostComponent,
HostPortal,
ClassComponent,
} = require('ReactTypeOfWork');
var {getUpdatePriority} = require('ReactFiberUpdateQueue');
var {resetContext} = require('ReactFiberContext');
var invariant = require('fbjs/lib/invariant');
if (__DEV__) {
var warning = require('fbjs/lib/warning');
var ReactFiberInstrumentation = require('ReactFiberInstrumentation');
var ReactDebugCurrentFiber = require('ReactDebugCurrentFiber');
var {
recordEffect,
recordScheduleUpdate,
startWorkTimer,
stopWorkTimer,
stopFailedWorkTimer,
startWorkLoopTimer,
stopWorkLoopTimer,
startCommitTimer,
stopCommitTimer,
startCommitHostEffectsTimer,
stopCommitHostEffectsTimer,
startCommitLifeCyclesTimer,
stopCommitLifeCyclesTimer,
} = require('ReactDebugFiberPerf');
var didWarnAboutStateTransition = false;
var warnAboutUpdateOnUnmounted = function(
instance: React$ComponentType<any>,
) {
const ctor = instance.constructor;
warning(
false,
'Can only update a mounted or mounting component. This usually means ' +
'you called setState, replaceState, or forceUpdate on an unmounted ' +
'component. This is a no-op.\n\nPlease check the code for the ' +
'%s component.',
(ctor && (ctor.displayName || ctor.name)) || 'ReactClass',
);
};
var warnAboutInvalidUpdates = function(instance: React$ComponentType<any>) {
switch (ReactDebugCurrentFiber.phase) {
case 'getChildContext':
warning(
false,
'setState(...): Cannot call setState() inside getChildContext()',
);
break;
case 'render':
if (didWarnAboutStateTransition) {
return;
}
didWarnAboutStateTransition = true;
warning(
false,
'Cannot update during an existing state transition (such as within ' +
"`render` or another component's constructor). Render methods should " +
'be a pure function of props and state; constructor side-effects are ' +
'an anti-pattern, but can be moved to `componentWillMount`.',
);
break;
}
};
}
var timeHeuristicForUnitOfWork = 1;
module.exports = function<T, P, I, TI, PI, C, CX, PL>(
config: HostConfig<T, P, I, TI, PI, C, CX, PL>,
) {
const hostContext = ReactFiberHostContext(config);
const hydrationContext: HydrationContext<C, CX> = ReactFiberHydrationContext(
config,
);
const {popHostContainer, popHostContext, resetHostContainer} = hostContext;
const {beginWork, beginFailedWork} = ReactFiberBeginWork(
config,
hostContext,
hydrationContext,
scheduleUpdate,
getPriorityContext,
);
const {completeWork} = ReactFiberCompleteWork(
config,
hostContext,
hydrationContext,
);
const {
commitPlacement,
commitDeletion,
commitWork,
commitLifeCycles,
commitAttachRef,
commitDetachRef,
} = ReactFiberCommitWork(config, captureError);
const {
scheduleDeferredCallback,
useSyncScheduling,
prepareForCommit,
resetAfterCommit,
} = config;
// The priority level to use when scheduling an update. We use NoWork to
// represent the default priority.
// TODO: Should we change this to an array instead of using the call stack?
// Might be less confusing.
let priorityContext: PriorityLevel = NoWork;
// Keeps track of whether we're currently in a work loop.
let isPerformingWork: boolean = false;
// Keeps track of whether the current deadline has expired.
let deadlineHasExpired: boolean = false;
// Keeps track of whether we should should batch sync updates.
let isBatchingUpdates: boolean = false;
// This is needed for the weird case where the initial mount is synchronous
// even inside batchedUpdates :(
let isUnbatchingUpdates: boolean = false;
// The next work in progress fiber that we're currently working on.
let nextUnitOfWork: Fiber | null = null;
let nextPriorityLevel: PriorityLevel = NoWork;
// The next fiber with an effect that we're currently committing.
let nextEffect: Fiber | null = null;
let pendingCommit: Fiber | null = null;
// Linked list of roots with scheduled work on them.
let nextScheduledRoot: FiberRoot | null = null;
let lastScheduledRoot: FiberRoot | null = null;
// Keep track of which host environment callbacks are scheduled.
let isCallbackScheduled: boolean = false;
// Keep track of which fibers have captured an error that need to be handled.
// Work is removed from this collection after componentDidCatch is called.
let capturedErrors: Map<Fiber, CapturedError> | null = null;
// Keep track of which fibers have failed during the current batch of work.
// This is a different set than capturedErrors, because it is not reset until
// the end of the batch. This is needed to propagate errors correctly if a
// subtree fails more than once.
let failedBoundaries: Set<Fiber> | null = null;
// Error boundaries that captured an error during the current commit.
let commitPhaseBoundaries: Set<Fiber> | null = null;
let firstUncaughtError: mixed | null = null;
let didFatal: boolean = false;
let isCommitting: boolean = false;
let isUnmounting: boolean = false;
// Use these to prevent an infinite loop of nested updates
const NESTED_UPDATE_LIMIT = 1000;
let nestedUpdateCount: number = 0;
let nextRenderedTree: FiberRoot | null = null;
function resetContextStack() {
// Reset the stack
reset();
// Reset the cursors
resetContext();
resetHostContainer();
}
// resetNextUnitOfWork mutates the current priority context. It is reset after
// after the workLoop exits, so never call resetNextUnitOfWork from outside
// the work loop.
function resetNextUnitOfWork() {
// Clear out roots with no more work on them, or if they have uncaught errors
while (
nextScheduledRoot !== null &&
nextScheduledRoot.current.pendingWorkPriority === NoWork
) {
// Unschedule this root.
nextScheduledRoot.isScheduled = false;
// Read the next pointer now.
// We need to clear it in case this root gets scheduled again later.
const next = nextScheduledRoot.nextScheduledRoot;
nextScheduledRoot.nextScheduledRoot = null;
// Exit if we cleared all the roots and there's no work to do.
if (nextScheduledRoot === lastScheduledRoot) {
nextScheduledRoot = null;
lastScheduledRoot = null;
nextPriorityLevel = NoWork;
return null;
}
// Continue with the next root.
// If there's no work on it, it will get unscheduled too.
nextScheduledRoot = next;
}
let root = nextScheduledRoot;
let highestPriorityRoot = null;
let highestPriorityLevel = NoWork;
while (root !== null) {
if (
root.current.pendingWorkPriority !== NoWork &&
(highestPriorityLevel === NoWork ||
highestPriorityLevel > root.current.pendingWorkPriority)
) {
highestPriorityLevel = root.current.pendingWorkPriority;
highestPriorityRoot = root;
}
// We didn't find anything to do in this root, so let's try the next one.
root = root.nextScheduledRoot;
}
if (highestPriorityRoot !== null) {
nextPriorityLevel = highestPriorityLevel;
// Before we start any new work, let's make sure that we have a fresh
// stack to work from.
// TODO: This call is buried a bit too deep. It would be nice to have
// a single point which happens right before any new work and
// unfortunately this is it.
resetContextStack();
nextUnitOfWork = createWorkInProgress(
highestPriorityRoot.current,
highestPriorityLevel,
);
if (highestPriorityRoot !== nextRenderedTree) {
// We've switched trees. Reset the nested update counter.
nestedUpdateCount = 0;
nextRenderedTree = highestPriorityRoot;
}
return;
}
nextPriorityLevel = NoWork;
nextUnitOfWork = null;
nextRenderedTree = null;
return;
}
function commitAllHostEffects() {
while (nextEffect !== null) {
if (__DEV__) {
ReactDebugCurrentFiber.setCurrentFiber(nextEffect);
recordEffect();
}
const effectTag = nextEffect.effectTag;
if (effectTag & ContentReset) {
config.resetTextContent(nextEffect.stateNode);
}
if (effectTag & Ref) {
const current = nextEffect.alternate;
if (current !== null) {
commitDetachRef(current);
}
}
// The following switch statement is only concerned about placement,
// updates, and deletions. To avoid needing to add a case for every
// possible bitmap value, we remove the secondary effects from the
// effect tag and switch on that value.
let primaryEffectTag =
effectTag & ~(Callback | Err | ContentReset | Ref | PerformedWork);
switch (primaryEffectTag) {
case Placement: {
commitPlacement(nextEffect);
// Clear the "placement" from effect tag so that we know that this is inserted, before
// any life-cycles like componentDidMount gets called.
// TODO: findDOMNode doesn't rely on this any more but isMounted
// does and isMounted is deprecated anyway so we should be able
// to kill this.
nextEffect.effectTag &= ~Placement;
break;
}
case PlacementAndUpdate: {
// Placement
commitPlacement(nextEffect);
// Clear the "placement" from effect tag so that we know that this is inserted, before
// any life-cycles like componentDidMount gets called.
nextEffect.effectTag &= ~Placement;
// Update
const current = nextEffect.alternate;
commitWork(current, nextEffect);
break;
}
case Update: {
const current = nextEffect.alternate;
commitWork(current, nextEffect);
break;
}
case Deletion: {
isUnmounting = true;
commitDeletion(nextEffect);
isUnmounting = false;
break;
}
}
nextEffect = nextEffect.nextEffect;
}
if (__DEV__) {
ReactDebugCurrentFiber.resetCurrentFiber();
}
}
function commitAllLifeCycles() {
while (nextEffect !== null) {
const effectTag = nextEffect.effectTag;
// Use Task priority for lifecycle updates
if (effectTag & (Update | Callback)) {
if (__DEV__) {
recordEffect();
}
const current = nextEffect.alternate;
commitLifeCycles(current, nextEffect);
}
if (effectTag & Ref) {
if (__DEV__) {
recordEffect();
}
commitAttachRef(nextEffect);
}
if (effectTag & Err) {
if (__DEV__) {
recordEffect();
}
commitErrorHandling(nextEffect);
}
const next = nextEffect.nextEffect;
// Ensure that we clean these up so that we don't accidentally keep them.
// I'm not actually sure this matters because we can't reset firstEffect
// and lastEffect since they're on every node, not just the effectful
// ones. So we have to clean everything as we reuse nodes anyway.
nextEffect.nextEffect = null;
// Ensure that we reset the effectTag here so that we can rely on effect
// tags to reason about the current life-cycle.
nextEffect = next;
}
}
function commitAllWork(finishedWork: Fiber) {
// We keep track of this so that captureError can collect any boundaries
// that capture an error during the commit phase. The reason these aren't
// local to this function is because errors that occur during cWU are
// captured elsewhere, to prevent the unmount from being interrupted.
isCommitting = true;
if (__DEV__) {
startCommitTimer();
}
pendingCommit = null;
const root: FiberRoot = (finishedWork.stateNode: any);
invariant(
root.current !== finishedWork,
'Cannot commit the same tree as before. This is probably a bug ' +
'related to the return field. This error is likely caused by a bug ' +
'in React. Please file an issue.',
);
if (
nextPriorityLevel === SynchronousPriority ||
nextPriorityLevel === TaskPriority
) {
// Keep track of the number of iterations to prevent an infinite
// update loop.
nestedUpdateCount++;
}
// Reset this to null before calling lifecycles
ReactCurrentOwner.current = null;
let firstEffect;
if (finishedWork.effectTag > PerformedWork) {
// A fiber's effect list consists only of its children, not itself. So if
// the root has an effect, we need to add it to the end of the list. The
// resulting list is the set that would belong to the root's parent, if
// it had one; that is, all the effects in the tree including the root.
if (finishedWork.lastEffect !== null) {
finishedWork.lastEffect.nextEffect = finishedWork;
firstEffect = finishedWork.firstEffect;
} else {
firstEffect = finishedWork;
}
} else {
// There is no effect on the root.
firstEffect = finishedWork.firstEffect;
}
prepareForCommit();
// Commit all the side-effects within a tree. We'll do this in two passes.
// The first pass performs all the host insertions, updates, deletions and
// ref unmounts.
nextEffect = firstEffect;
if (__DEV__) {
startCommitHostEffectsTimer();
}
while (nextEffect !== null) {
let didError = false;
let error;
if (__DEV__) {
invokeGuardedCallback(null, commitAllHostEffects, null);
if (hasCaughtError()) {
didError = true;
error = clearCaughtError();
}
} else {
try {
commitAllHostEffects();
} catch (e) {
didError = true;
error = e;
}
}
if (didError) {
invariant(
nextEffect !== null,
'Should have next effect. This error is likely caused by a bug ' +
'in React. Please file an issue.',
);
captureError(nextEffect, error);
// Clean-up
if (nextEffect !== null) {
nextEffect = nextEffect.nextEffect;
}
}
}
if (__DEV__) {
stopCommitHostEffectsTimer();
}
resetAfterCommit();
// The work-in-progress tree is now the current tree. This must come after
// the first pass of the commit phase, so that the previous tree is still
// current during componentWillUnmount, but before the second pass, so that
// the finished work is current during componentDidMount/Update.
root.current = finishedWork;
// In the second pass we'll perform all life-cycles and ref callbacks.
// Life-cycles happen as a separate pass so that all placements, updates,
// and deletions in the entire tree have already been invoked.
// This pass also triggers any renderer-specific initial effects.
nextEffect = firstEffect;
if (__DEV__) {
startCommitLifeCyclesTimer();
}
while (nextEffect !== null) {
let didError = false;
let error;
if (__DEV__) {
invokeGuardedCallback(null, commitAllLifeCycles, null);
if (hasCaughtError()) {
didError = true;
error = clearCaughtError();
}
} else {
try {
commitAllLifeCycles();
} catch (e) {
didError = true;
error = e;
}
}
if (didError) {
invariant(
nextEffect !== null,
'Should have next effect. This error is likely caused by a bug ' +
'in React. Please file an issue.',
);
captureError(nextEffect, error);
if (nextEffect !== null) {
nextEffect = nextEffect.nextEffect;
}
}
}
isCommitting = false;
if (__DEV__) {
stopCommitLifeCyclesTimer();
stopCommitTimer();
}
if (typeof onCommitRoot === 'function') {
onCommitRoot(finishedWork.stateNode);
}
if (__DEV__ && ReactFiberInstrumentation.debugTool) {
ReactFiberInstrumentation.debugTool.onCommitWork(finishedWork);
}
// If we caught any errors during this commit, schedule their boundaries
// to update.
if (commitPhaseBoundaries) {
commitPhaseBoundaries.forEach(scheduleErrorRecovery);
commitPhaseBoundaries = null;
}
// This tree is done. Reset the unit of work pointer to the next highest
// priority root. If there's no more work left, the pointer is set to null.
resetNextUnitOfWork();
}
function resetWorkPriority(
workInProgress: Fiber,
renderPriority: PriorityLevel,
) {
if (
workInProgress.pendingWorkPriority !== NoWork &&
workInProgress.pendingWorkPriority > renderPriority
) {
// This was a down-prioritization. Don't bubble priority from children.
return;
}
// Check for pending update priority.
let newPriority = getUpdatePriority(workInProgress);
// TODO: Coroutines need to visit stateNode
let child = workInProgress.child;
while (child !== null) {
// Ensure that remaining work priority bubbles up.
newPriority = largerPriority(newPriority, child.pendingWorkPriority);
child = child.sibling;
}
workInProgress.pendingWorkPriority = newPriority;
}
function completeUnitOfWork(workInProgress: Fiber): Fiber | null {
while (true) {
// The current, flushed, state of this fiber is the alternate.
// Ideally nothing should rely on this, but relying on it here
// means that we don't need an additional field on the work in
// progress.
const current = workInProgress.alternate;
if (__DEV__) {
ReactDebugCurrentFiber.setCurrentFiber(workInProgress);
}
const next = completeWork(current, workInProgress, nextPriorityLevel);
if (__DEV__) {
ReactDebugCurrentFiber.resetCurrentFiber();
}
const returnFiber = workInProgress.return;
const siblingFiber = workInProgress.sibling;
resetWorkPriority(workInProgress, nextPriorityLevel);
if (next !== null) {
if (__DEV__) {
stopWorkTimer(workInProgress);
}
if (__DEV__ && ReactFiberInstrumentation.debugTool) {
ReactFiberInstrumentation.debugTool.onCompleteWork(workInProgress);
}
// If completing this work spawned new work, do that next. We'll come
// back here again.
return next;
}
if (returnFiber !== null) {
// Append all the effects of the subtree and this fiber onto the effect
// list of the parent. The completion order of the children affects the
// side-effect order.
if (returnFiber.firstEffect === null) {
returnFiber.firstEffect = workInProgress.firstEffect;
}
if (workInProgress.lastEffect !== null) {
if (returnFiber.lastEffect !== null) {
returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
}
returnFiber.lastEffect = workInProgress.lastEffect;
}
// If this fiber had side-effects, we append it AFTER the children's
// side-effects. We can perform certain side-effects earlier if
// needed, by doing multiple passes over the effect list. We don't want
// to schedule our own side-effect on our own list because if end up
// reusing children we'll schedule this effect onto itself since we're
// at the end.
const effectTag = workInProgress.effectTag;
// Skip both NoWork and PerformedWork tags when creating the effect list.
// PerformedWork effect is read by React DevTools but shouldn't be committed.
if (effectTag > PerformedWork) {
if (returnFiber.lastEffect !== null) {
returnFiber.lastEffect.nextEffect = workInProgress;
} else {
returnFiber.firstEffect = workInProgress;
}
returnFiber.lastEffect = workInProgress;
}
}
if (__DEV__) {
stopWorkTimer(workInProgress);
}
if (__DEV__ && ReactFiberInstrumentation.debugTool) {
ReactFiberInstrumentation.debugTool.onCompleteWork(workInProgress);
}
if (siblingFiber !== null) {
// If there is more work to do in this returnFiber, do that next.
return siblingFiber;
} else if (returnFiber !== null) {
// If there's no more work in this returnFiber. Complete the returnFiber.
workInProgress = returnFiber;
continue;
} else {
// We've reached the root. Mark the root as pending commit. Depending
// on how much time we have left, we'll either commit it now or in
// the next frame.
pendingCommit = workInProgress;
return null;
}
}
// Without this explicit null return Flow complains of invalid return type
// TODO Remove the above while(true) loop
// eslint-disable-next-line no-unreachable
return null;
}
function performUnitOfWork(workInProgress: Fiber): Fiber | null {
// The current, flushed, state of this fiber is the alternate.
// Ideally nothing should rely on this, but relying on it here
// means that we don't need an additional field on the work in
// progress.
const current = workInProgress.alternate;
// See if beginning this work spawns more work.
if (__DEV__) {
startWorkTimer(workInProgress);
ReactDebugCurrentFiber.setCurrentFiber(workInProgress);
}
let next = beginWork(current, workInProgress, nextPriorityLevel);
if (__DEV__) {
ReactDebugCurrentFiber.resetCurrentFiber();
}
if (__DEV__ && ReactFiberInstrumentation.debugTool) {
ReactFiberInstrumentation.debugTool.onBeginWork(workInProgress);
}
if (next === null) {
// If this doesn't spawn new work, complete the current work.
next = completeUnitOfWork(workInProgress);
}
ReactCurrentOwner.current = null;
return next;
}
function performFailedUnitOfWork(workInProgress: Fiber): Fiber | null {
// The current, flushed, state of this fiber is the alternate.
// Ideally nothing should rely on this, but relying on it here
// means that we don't need an additional field on the work in
// progress.
const current = workInProgress.alternate;
// See if beginning this work spawns more work.
if (__DEV__) {
startWorkTimer(workInProgress);
ReactDebugCurrentFiber.setCurrentFiber(workInProgress);
}
let next = beginFailedWork(current, workInProgress, nextPriorityLevel);
if (__DEV__) {
ReactDebugCurrentFiber.resetCurrentFiber();
}
if (__DEV__ && ReactFiberInstrumentation.debugTool) {
ReactFiberInstrumentation.debugTool.onBeginWork(workInProgress);
}
if (next === null) {
// If this doesn't spawn new work, complete the current work.
next = completeUnitOfWork(workInProgress);
}
ReactCurrentOwner.current = null;
return next;
}
function performDeferredWork(deadline: Deadline) {
performWork(OffscreenPriority, deadline);
}
function handleCommitPhaseErrors() {
// This is a special work loop for handling commit phase errors. It's
// similar to the syncrhonous work loop, but does an additional check on
// each fiber to see if it's an error boundary with an unhandled error. If
// so, it uses a forked version of performUnitOfWork that unmounts the
// failed subtree.
//
// The loop stops once the children have unmounted and error lifecycles are
// called. Then we return to the regular flow.
if (
capturedErrors !== null &&
capturedErrors.size > 0 &&
nextPriorityLevel === TaskPriority
) {
while (nextUnitOfWork !== null) {
if (hasCapturedError(nextUnitOfWork)) {
// Use a forked version of performUnitOfWork
nextUnitOfWork = performFailedUnitOfWork(nextUnitOfWork);
} else {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
if (nextUnitOfWork === null) {
invariant(
pendingCommit !== null,
'Should have a pending commit. This error is likely caused by ' +
'a bug in React. Please file an issue.',
);
// We just completed a root. Commit it now.
priorityContext = TaskPriority;
commitAllWork(pendingCommit);
priorityContext = nextPriorityLevel;
if (
capturedErrors === null ||
capturedErrors.size === 0 ||
nextPriorityLevel !== TaskPriority
) {
// There are no more unhandled errors. We can exit this special
// work loop. If there's still additional work, we'll perform it
// using one of the normal work loops.
break;
}
// The commit phase produced additional errors. Continue working.
}
}
}
}
function workLoop(
minPriorityLevel: PriorityLevel,
deadline: Deadline | null,
) {
if (pendingCommit !== null) {
priorityContext = TaskPriority;
commitAllWork(pendingCommit);
handleCommitPhaseErrors();
} else if (nextUnitOfWork === null) {
resetNextUnitOfWork();
}
if (nextPriorityLevel === NoWork || nextPriorityLevel > minPriorityLevel) {
return;
}
// During the render phase, updates should have the same priority at which
// we're rendering.
priorityContext = nextPriorityLevel;
loop: do {
if (nextPriorityLevel <= TaskPriority) {
// Flush all synchronous and task work.
while (nextUnitOfWork !== null) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
if (nextUnitOfWork === null) {
invariant(
pendingCommit !== null,
'Should have a pending commit. This error is likely caused by ' +
'a bug in React. Please file an issue.',
);
// We just completed a root. Commit it now.
priorityContext = TaskPriority;
commitAllWork(pendingCommit);
priorityContext = nextPriorityLevel;
// Clear any errors that were scheduled during the commit phase.
handleCommitPhaseErrors();
// The priority level may have changed. Check again.
if (
nextPriorityLevel === NoWork ||
nextPriorityLevel > minPriorityLevel ||
nextPriorityLevel > TaskPriority
) {
// The priority level does not match.
break;
}
}
}
} else if (deadline !== null) {
// Flush asynchronous work until the deadline expires.
while (nextUnitOfWork !== null && !deadlineHasExpired) {
if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
// In a deferred work batch, iff nextUnitOfWork returns null, we just
// completed a root and a pendingCommit exists. Logically, we could
// omit either of the checks in the following condition, but we need
// both to satisfy Flow.
if (nextUnitOfWork === null) {
invariant(
pendingCommit !== null,
'Should have a pending commit. This error is likely caused by ' +
'a bug in React. Please file an issue.',
);
// We just completed a root. If we have time, commit it now.
// Otherwise, we'll commit it in the next frame.
if (deadline.timeRemaining() > timeHeuristicForUnitOfWork) {
priorityContext = TaskPriority;
commitAllWork(pendingCommit);
priorityContext = nextPriorityLevel;
// Clear any errors that were scheduled during the commit phase.
handleCommitPhaseErrors();
// The priority level may have changed. Check again.
if (
nextPriorityLevel === NoWork ||
nextPriorityLevel > minPriorityLevel ||
nextPriorityLevel < HighPriority
) {
// The priority level does not match.
break;
}
} else {
deadlineHasExpired = true;
}
}
} else {
deadlineHasExpired = true;
}
}
}
// There might be work left. Depending on the priority, we should
// either perform it now or schedule a callback to perform it later.
switch (nextPriorityLevel) {
case SynchronousPriority:
case TaskPriority:
// We have remaining synchronous or task work. Keep performing it,
// regardless of whether we're inside a callback.
if (nextPriorityLevel <= minPriorityLevel) {
continue loop;
}
break loop;
case HighPriority:
case LowPriority:
case OffscreenPriority:
// We have remaining async work.
if (deadline === null) {
// We're not inside a callback. Exit and perform the work during
// the next callback.
break loop;
}
// We are inside a callback.
if (!deadlineHasExpired && nextPriorityLevel <= minPriorityLevel) {
// We still have time. Keep working.
continue loop;
}
// We've run out of time. Exit.
break loop;
case NoWork:
// No work left. We can exit.
break loop;
default:
invariant(
false,
'Switch statement should be exhuastive. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
} while (true);
}
function performWorkCatchBlock(
failedWork: Fiber,
boundary: Fiber,
minPriorityLevel: PriorityLevel,
deadline: Deadline | null,
) {
// We're going to restart the error boundary that captured the error.
// Conceptually, we're unwinding the stack. We need to unwind the
// context stack, too.
unwindContexts(failedWork, boundary);
// Restart the error boundary using a forked version of
// performUnitOfWork that deletes the boundary's children. The entire
// failed subree will be unmounted. During the commit phase, a special
// lifecycle method is called on the error boundary, which triggers
// a re-render.
nextUnitOfWork = performFailedUnitOfWork(boundary);
// Continue working.
workLoop(minPriorityLevel, deadline);
}
function performWork(
minPriorityLevel: PriorityLevel,
deadline: Deadline | null,
) {
if (__DEV__) {
startWorkLoopTimer();
}
invariant(
!isPerformingWork,
'performWork was called recursively. This error is likely caused ' +
'by a bug in React. Please file an issue.',
);
isPerformingWork = true;
// The priority context changes during the render phase. We'll need to
// reset it at the end.
const previousPriorityContext = priorityContext;
let didError = false;
let error = null;
if (__DEV__) {
invokeGuardedCallback(null, workLoop, null, minPriorityLevel, deadline);
if (hasCaughtError()) {
didError = true;