-
Notifications
You must be signed in to change notification settings - Fork 47.5k
/
Copy pathReactFiberCommitWork.js
5402 lines (5097 loc) · 179 KB
/
ReactFiberCommitWork.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) 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 {
Instance,
TextInstance,
SuspenseInstance,
Container,
HoistableRoot,
FormInstance,
InstanceMeasurement,
Props,
} from './ReactFiberConfig';
import type {Fiber, FiberRoot} from './ReactInternalTypes';
import type {Lanes} from './ReactFiberLane';
import {
includesOnlyViewTransitionEligibleLanes,
SyncLane,
} from './ReactFiberLane';
import type {SuspenseState, RetryQueue} from './ReactFiberSuspenseComponent';
import type {UpdateQueue} from './ReactFiberClassUpdateQueue';
import type {FunctionComponentUpdateQueue} from './ReactFiberHooks';
import type {Wakeable} from 'shared/ReactTypes';
import {isOffscreenManual} from './ReactFiberActivityComponent';
import type {
OffscreenState,
OffscreenInstance,
OffscreenQueue,
OffscreenProps,
} from './ReactFiberActivityComponent';
import type {Cache} from './ReactFiberCacheComponent';
import type {RootState} from './ReactFiberRoot';
import type {
Transition,
TracingMarkerInstance,
TransitionAbort,
} from './ReactFiberTracingMarkerComponent';
import type {
ViewTransitionProps,
ViewTransitionState,
} from './ReactFiberViewTransitionComponent';
import {
alwaysThrottleRetries,
enableCreateEventHandleAPI,
enableHiddenSubtreeInsertionEffectCleanup,
enablePersistedModeClonedFlag,
enableProfilerTimer,
enableProfilerCommitHooks,
enableSuspenseCallback,
enableScopeAPI,
enableUpdaterTracking,
enableTransitionTracing,
enableUseEffectEventHook,
enableLegacyHidden,
disableLegacyMode,
enableComponentPerformanceTrack,
enableViewTransition,
} from 'shared/ReactFeatureFlags';
import {
FunctionComponent,
ForwardRef,
ClassComponent,
HostRoot,
HostComponent,
HostHoistable,
HostSingleton,
HostText,
HostPortal,
Profiler,
SuspenseComponent,
DehydratedFragment,
IncompleteClassComponent,
MemoComponent,
SimpleMemoComponent,
SuspenseListComponent,
ScopeComponent,
OffscreenComponent,
LegacyHiddenComponent,
CacheComponent,
TracingMarkerComponent,
ViewTransitionComponent,
} from './ReactWorkTags';
import {
NoFlags,
ContentReset,
Placement,
ChildDeletion,
Snapshot,
Update,
Callback,
Ref,
Hydrating,
Passive,
BeforeMutationMask,
BeforeMutationTransitionMask,
MutationMask,
LayoutMask,
PassiveMask,
PassiveTransitionMask,
Visibility,
ShouldSuspendCommit,
MaySuspendCommit,
FormReset,
Cloned,
PerformedWork,
ForceClientRender,
DidCapture,
ViewTransitionStatic,
AffectedParentLayout,
ViewTransitionNamedStatic,
} from './ReactFiberFlags';
import {
commitStartTime,
pushNestedEffectDurations,
popNestedEffectDurations,
bubbleNestedEffectDurations,
resetComponentEffectTimers,
pushComponentEffectStart,
popComponentEffectStart,
pushComponentEffectErrors,
popComponentEffectErrors,
componentEffectStartTime,
componentEffectEndTime,
componentEffectDuration,
componentEffectErrors,
} from './ReactProfilerTimer';
import {
logComponentRender,
logComponentErrored,
logComponentEffect,
} from './ReactFiberPerformanceTrack';
import {ConcurrentMode, NoMode, ProfileMode} from './ReactTypeOfMode';
import {deferHiddenCallbacks} from './ReactFiberClassUpdateQueue';
import {
supportsMutation,
supportsPersistence,
supportsHydration,
supportsResources,
supportsSingletons,
clearSuspenseBoundary,
clearSuspenseBoundaryFromContainer,
createContainerChildSet,
clearContainer,
prepareScopeUpdate,
prepareForCommit,
beforeActiveInstanceBlur,
detachDeletedInstance,
getHoistableRoot,
acquireResource,
releaseResource,
hydrateHoistable,
mountHoistable,
unmountHoistable,
prepareToCommitHoistables,
suspendInstance,
suspendResource,
resetFormInstance,
registerSuspenseInstanceRetry,
applyViewTransitionName,
restoreViewTransitionName,
cancelViewTransitionName,
cancelRootViewTransitionName,
restoreRootViewTransitionName,
measureInstance,
hasInstanceChanged,
hasInstanceAffectedParent,
wasInstanceInViewport,
isSingletonScope,
} from './ReactFiberConfig';
import {
captureCommitPhaseError,
resolveRetryWakeable,
markCommitTimeOfFallback,
restorePendingUpdaters,
addTransitionStartCallbackToPendingTransition,
addTransitionProgressCallbackToPendingTransition,
addTransitionCompleteCallbackToPendingTransition,
addMarkerProgressCallbackToPendingTransition,
addMarkerIncompleteCallbackToPendingTransition,
addMarkerCompleteCallbackToPendingTransition,
retryDehydratedSuspenseBoundary,
scheduleViewTransitionEvent,
} from './ReactFiberWorkLoop';
import {
HasEffect as HookHasEffect,
Layout as HookLayout,
Insertion as HookInsertion,
Passive as HookPassive,
} from './ReactHookEffectTags';
import {doesFiberContain} from './ReactFiberTreeReflection';
import {isDevToolsPresent, onCommitUnmount} from './ReactFiberDevToolsHook';
import {releaseCache, retainCache} from './ReactFiberCacheComponent';
import {clearTransitionsForLanes} from './ReactFiberLane';
import {
OffscreenVisible,
OffscreenDetached,
OffscreenPassiveEffectsConnected,
} from './ReactFiberActivityComponent';
import {
getViewTransitionName,
getViewTransitionClassName,
} from './ReactFiberViewTransitionComponent';
import {
TransitionRoot,
TransitionTracingMarker,
} from './ReactFiberTracingMarkerComponent';
import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop';
import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates';
import {
commitHookLayoutEffects,
commitHookLayoutUnmountEffects,
commitHookEffectListMount,
commitHookEffectListUnmount,
commitHookPassiveMountEffects,
commitHookPassiveUnmountEffects,
commitClassLayoutLifecycles,
commitClassDidMount,
commitClassCallbacks,
commitClassHiddenCallbacks,
commitClassSnapshot,
safelyCallComponentWillUnmount,
safelyAttachRef,
safelyDetachRef,
commitProfilerUpdate,
commitProfilerPostCommit,
commitRootCallbacks,
} from './ReactFiberCommitEffects';
import {
commitHostMount,
commitHostUpdate,
commitHostTextUpdate,
commitHostResetTextContent,
commitShowHideHostInstance,
commitShowHideHostTextInstance,
commitHostPlacement,
commitHostRootContainerChildren,
commitHostPortalContainerChildren,
commitHostHydratedContainer,
commitHostHydratedSuspense,
commitHostRemoveChildFromContainer,
commitHostRemoveChild,
commitHostSingletonAcquisition,
commitHostSingletonRelease,
} from './ReactFiberCommitHostEffects';
import {
viewTransitionMutationContext,
pushMutationContext,
popMutationContext,
} from './ReactFiberMutationTracking';
// Used during the commit phase to track the state of the Offscreen component stack.
// Allows us to avoid traversing the return path to find the nearest Offscreen ancestor.
let offscreenSubtreeIsHidden: boolean = false;
let offscreenSubtreeWasHidden: boolean = false;
// Used to track if a form needs to be reset at the end of the mutation phase.
let needsFormReset = false;
const PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
let nextEffect: Fiber | null = null;
// Used for Profiling builds to track updaters.
let inProgressLanes: Lanes | null = null;
let inProgressRoot: FiberRoot | null = null;
let focusedInstanceHandle: null | Fiber = null;
export let shouldFireAfterActiveInstanceBlur: boolean = false;
export let shouldStartViewTransition: boolean = false;
// This tracks named ViewTransition components found in the accumulateSuspenseyCommit
// phase that might need to find deleted pairs in the beforeMutation phase.
let appearingViewTransitions: Map<string, ViewTransitionState> | null = null;
// Used during the commit phase to track whether a parent ViewTransition component
// might have been affected by any mutations / relayouts below.
let viewTransitionContextChanged: boolean = false;
// We can't cancel view transition children until we know that their parent also
// don't need to transition.
let viewTransitionCancelableChildren: null | Array<Instance | string | Props> =
null; // tupled array where each entry is [instance: Instance, oldName: string, props: Props]
export function commitBeforeMutationEffects(
root: FiberRoot,
firstChild: Fiber,
committedLanes: Lanes,
): void {
focusedInstanceHandle = prepareForCommit(root.containerInfo);
shouldFireAfterActiveInstanceBlur = false;
shouldStartViewTransition = false;
const isViewTransitionEligible =
enableViewTransition &&
includesOnlyViewTransitionEligibleLanes(committedLanes);
nextEffect = firstChild;
commitBeforeMutationEffects_begin(isViewTransitionEligible);
// We no longer need to track the active instance fiber
focusedInstanceHandle = null;
// We've found any matched pairs and can now reset.
appearingViewTransitions = null;
}
function commitBeforeMutationEffects_begin(isViewTransitionEligible: boolean) {
// If this commit is eligible for a View Transition we look into all mutated subtrees.
// TODO: We could optimize this by marking these with the Snapshot subtree flag in the render phase.
const subtreeMask = isViewTransitionEligible
? BeforeMutationTransitionMask
: BeforeMutationMask;
while (nextEffect !== null) {
const fiber = nextEffect;
// This phase is only used for beforeActiveInstanceBlur.
// Let's skip the whole loop if it's off.
if (enableCreateEventHandleAPI || isViewTransitionEligible) {
// TODO: Should wrap this in flags check, too, as optimization
const deletions = fiber.deletions;
if (deletions !== null) {
for (let i = 0; i < deletions.length; i++) {
const deletion = deletions[i];
commitBeforeMutationEffectsDeletion(
deletion,
isViewTransitionEligible,
);
}
}
}
if (
enableViewTransition &&
fiber.alternate === null &&
(fiber.flags & Placement) !== NoFlags
) {
// Skip before mutation effects of the children because we don't want
// to trigger updates of any nested view transitions and we shouldn't
// have any other before mutation effects since snapshot effects are
// only applied to updates. TODO: Model this using only flags.
commitBeforeMutationEffects_complete(isViewTransitionEligible);
continue;
}
// TODO: This should really unify with the switch in commitBeforeMutationEffectsOnFiber recursively.
if (enableViewTransition && fiber.tag === OffscreenComponent) {
const isModernRoot =
disableLegacyMode || (fiber.mode & ConcurrentMode) !== NoMode;
if (isModernRoot) {
const current = fiber.alternate;
const isHidden = fiber.memoizedState !== null;
if (isHidden) {
if (
current !== null &&
current.memoizedState === null &&
isViewTransitionEligible
) {
// Was previously mounted as visible but is now hidden.
commitExitViewTransitions(current);
}
// Skip before mutation effects of the children because they're hidden.
commitBeforeMutationEffects_complete(isViewTransitionEligible);
continue;
} else if (current !== null && current.memoizedState !== null) {
// Was previously mounted as hidden but is now visible.
// Skip before mutation effects of the children because we don't want
// to trigger updates of any nested view transitions and we shouldn't
// have any other before mutation effects since snapshot effects are
// only applied to updates. TODO: Model this using only flags.
commitBeforeMutationEffects_complete(isViewTransitionEligible);
continue;
}
}
}
const child = fiber.child;
if ((fiber.subtreeFlags & subtreeMask) !== NoFlags && child !== null) {
child.return = fiber;
nextEffect = child;
} else {
if (isViewTransitionEligible) {
// We are inside an updated subtree. Any mutations that affected the
// parent HostInstance's layout or set of children (such as reorders)
// might have also affected the positioning or size of the inner
// ViewTransitions. Therefore we need to find them inside.
commitNestedViewTransitions(fiber);
}
commitBeforeMutationEffects_complete(isViewTransitionEligible);
}
}
}
function commitBeforeMutationEffects_complete(
isViewTransitionEligible: boolean,
) {
while (nextEffect !== null) {
const fiber = nextEffect;
commitBeforeMutationEffectsOnFiber(fiber, isViewTransitionEligible);
const sibling = fiber.sibling;
if (sibling !== null) {
sibling.return = fiber.return;
nextEffect = sibling;
return;
}
nextEffect = fiber.return;
}
}
function commitBeforeMutationEffectsOnFiber(
finishedWork: Fiber,
isViewTransitionEligible: boolean,
) {
const current = finishedWork.alternate;
const flags = finishedWork.flags;
if (enableCreateEventHandleAPI) {
if (!shouldFireAfterActiveInstanceBlur && focusedInstanceHandle !== null) {
// Check to see if the focused element was inside of a hidden (Suspense) subtree.
// TODO: Move this out of the hot path using a dedicated effect tag.
if (
finishedWork.tag === SuspenseComponent &&
isSuspenseBoundaryBeingHidden(current, finishedWork) &&
// $FlowFixMe[incompatible-call] found when upgrading Flow
doesFiberContain(finishedWork, focusedInstanceHandle)
) {
shouldFireAfterActiveInstanceBlur = true;
beforeActiveInstanceBlur(finishedWork);
}
}
}
switch (finishedWork.tag) {
case FunctionComponent: {
if (enableUseEffectEventHook) {
if ((flags & Update) !== NoFlags) {
const updateQueue: FunctionComponentUpdateQueue | null =
(finishedWork.updateQueue: any);
const eventPayloads =
updateQueue !== null ? updateQueue.events : null;
if (eventPayloads !== null) {
for (let ii = 0; ii < eventPayloads.length; ii++) {
const {ref, nextImpl} = eventPayloads[ii];
ref.impl = nextImpl;
}
}
}
}
break;
}
case ForwardRef:
case SimpleMemoComponent: {
break;
}
case ClassComponent: {
if ((flags & Snapshot) !== NoFlags) {
if (current !== null) {
commitClassSnapshot(finishedWork, current);
}
}
break;
}
case HostRoot: {
if ((flags & Snapshot) !== NoFlags) {
if (supportsMutation) {
const root = finishedWork.stateNode;
clearContainer(root.containerInfo);
}
}
break;
}
case HostComponent:
case HostHoistable:
case HostSingleton:
case HostText:
case HostPortal:
case IncompleteClassComponent:
// Nothing to do for these component types
break;
case ViewTransitionComponent:
if (enableViewTransition) {
if (isViewTransitionEligible) {
if (current === null) {
// This is a new mount. We should have handled this as part of the
// Placement effect or it is deeper inside a entering transition.
} else if (
(finishedWork.subtreeFlags &
(Placement |
Update |
ChildDeletion |
ContentReset |
Visibility)) !==
NoFlags
) {
// Something mutated within this subtree. This might need to cause
// a cross-fade of this parent. We first assign old names to the
// previous tree in the before mutation phase in case we need to.
// TODO: This walks the tree that we might continue walking anyway.
// We should just stash the parent ViewTransitionComponent and continue
// walking the tree until we find HostComponent but to do that we need
// to use a stack which requires refactoring this phase.
commitBeforeUpdateViewTransition(current, finishedWork);
}
}
break;
}
// Fallthrough
default: {
if ((flags & Snapshot) !== NoFlags) {
throw new Error(
'This unit of work tag should not have side-effects. This error is ' +
'likely caused by a bug in React. Please file an issue.',
);
}
}
}
}
function commitBeforeMutationEffectsDeletion(
deletion: Fiber,
isViewTransitionEligible: boolean,
) {
if (enableCreateEventHandleAPI) {
// TODO (effects) It would be nice to avoid calling doesFiberContain()
// Maybe we can repurpose one of the subtreeFlags positions for this instead?
// Use it to store which part of the tree the focused instance is in?
// This assumes we can safely determine that instance during the "render" phase.
if (doesFiberContain(deletion, ((focusedInstanceHandle: any): Fiber))) {
shouldFireAfterActiveInstanceBlur = true;
beforeActiveInstanceBlur(deletion);
}
}
if (isViewTransitionEligible) {
commitExitViewTransitions(deletion);
}
}
let viewTransitionHostInstanceIdx = 0;
function applyViewTransitionToHostInstances(
child: null | Fiber,
name: string,
className: ?string,
collectMeasurements: null | Array<InstanceMeasurement>,
stopAtNestedViewTransitions: boolean,
): boolean {
if (!supportsMutation) {
return false;
}
let inViewport = false;
while (child !== null) {
if (child.tag === HostComponent) {
shouldStartViewTransition = true;
const instance: Instance = child.stateNode;
if (collectMeasurements !== null) {
const measurement = measureInstance(instance);
collectMeasurements.push(measurement);
if (wasInstanceInViewport(measurement)) {
inViewport = true;
}
} else if (!inViewport) {
if (wasInstanceInViewport(measureInstance(instance))) {
inViewport = true;
}
}
applyViewTransitionName(
instance,
viewTransitionHostInstanceIdx === 0
? name
: // If we have multiple Host Instances below, we add a suffix to the name to give
// each one a unique name.
name + '_' + viewTransitionHostInstanceIdx,
className,
);
viewTransitionHostInstanceIdx++;
} else if (
child.tag === OffscreenComponent &&
child.memoizedState !== null
) {
// Skip any hidden subtrees. They were or are effectively not there.
} else if (
child.tag === ViewTransitionComponent &&
stopAtNestedViewTransitions
) {
// Skip any nested view transitions for updates since in that case the
// inner most one is the one that handles the update.
} else {
if (
applyViewTransitionToHostInstances(
child.child,
name,
className,
collectMeasurements,
stopAtNestedViewTransitions,
)
) {
inViewport = true;
}
}
child = child.sibling;
}
return inViewport;
}
function restoreViewTransitionOnHostInstances(
child: null | Fiber,
stopAtNestedViewTransitions: boolean,
): void {
if (!supportsMutation) {
return;
}
while (child !== null) {
if (child.tag === HostComponent) {
const instance: Instance = child.stateNode;
restoreViewTransitionName(instance, child.memoizedProps);
} else if (
child.tag === OffscreenComponent &&
child.memoizedState !== null
) {
// Skip any hidden subtrees. They were or are effectively not there.
} else if (
child.tag === ViewTransitionComponent &&
stopAtNestedViewTransitions
) {
// Skip any nested view transitions for updates since in that case the
// inner most one is the one that handles the update.
} else {
restoreViewTransitionOnHostInstances(
child.child,
stopAtNestedViewTransitions,
);
}
child = child.sibling;
}
}
function commitAppearingPairViewTransitions(placement: Fiber): void {
if ((placement.subtreeFlags & ViewTransitionNamedStatic) === NoFlags) {
// This has no named view transitions in its subtree.
return;
}
let child = placement.child;
while (child !== null) {
if (child.tag === OffscreenComponent && child.memoizedState === null) {
// This tree was already hidden so we skip it.
} else {
commitAppearingPairViewTransitions(child);
if (
child.tag === ViewTransitionComponent &&
(child.flags & ViewTransitionNamedStatic) !== NoFlags
) {
const instance: ViewTransitionState = child.stateNode;
if (instance.paired) {
const props: ViewTransitionProps = child.memoizedProps;
if (props.name == null || props.name === 'auto') {
throw new Error(
'Found a pair with an auto name. This is a bug in React.',
);
}
const name = props.name;
const className: ?string = getViewTransitionClassName(
props.className,
props.share,
);
if (className !== 'none') {
// We found a new appearing view transition with the same name as this deletion.
// We'll transition between them.
viewTransitionHostInstanceIdx = 0;
const inViewport = applyViewTransitionToHostInstances(
child.child,
name,
className,
null,
false,
);
if (!inViewport) {
// This boundary is exiting within the viewport but is going to leave the viewport.
// Instead, we treat this as an exit of the previous entry by reverting the new name.
// Ideally we could undo the old transition but it's now too late. It's also on its
// on snapshot. We have know was for it to paint onto the original group.
// TODO: This will lead to things unexpectedly having exit animations that normally
// wouldn't happen. Consider if we should just let this fly off the screen instead.
restoreViewTransitionOnHostInstances(child.child, false);
}
}
}
}
}
child = child.sibling;
}
}
function commitEnterViewTransitions(placement: Fiber): void {
if (placement.tag === ViewTransitionComponent) {
const state: ViewTransitionState = placement.stateNode;
const props: ViewTransitionProps = placement.memoizedProps;
const name = getViewTransitionName(props, state);
const className: ?string = getViewTransitionClassName(
props.className,
state.paired ? props.share : props.enter,
);
if (className !== 'none') {
viewTransitionHostInstanceIdx = 0;
const inViewport = applyViewTransitionToHostInstances(
placement.child,
name,
className,
null,
false,
);
if (!inViewport) {
// TODO: If this was part of a pair we will still run the onShare callback.
// Revert the transition names. This boundary is not in the viewport
// so we won't bother animating it.
restoreViewTransitionOnHostInstances(placement.child, false);
// TODO: Should we still visit the children in case a named one was in the viewport?
} else {
commitAppearingPairViewTransitions(placement);
if (!state.paired) {
scheduleViewTransitionEvent(placement, props.onEnter);
}
}
} else {
commitAppearingPairViewTransitions(placement);
}
} else if ((placement.subtreeFlags & ViewTransitionStatic) !== NoFlags) {
let child = placement.child;
while (child !== null) {
commitEnterViewTransitions(child);
child = child.sibling;
}
} else {
commitAppearingPairViewTransitions(placement);
}
}
function commitDeletedPairViewTransitions(deletion: Fiber): void {
if (
appearingViewTransitions === null ||
appearingViewTransitions.size === 0
) {
// We've found all.
return;
}
const pairs = appearingViewTransitions;
if ((deletion.subtreeFlags & ViewTransitionNamedStatic) === NoFlags) {
// This has no named view transitions in its subtree.
return;
}
let child = deletion.child;
while (child !== null) {
if (child.tag === OffscreenComponent && child.memoizedState === null) {
// This tree was already hidden so we skip it.
} else {
if (
child.tag === ViewTransitionComponent &&
(child.flags & ViewTransitionNamedStatic) !== NoFlags
) {
const props: ViewTransitionProps = child.memoizedProps;
const name = props.name;
if (name != null && name !== 'auto') {
const pair = pairs.get(name);
if (pair !== undefined) {
const className: ?string = getViewTransitionClassName(
props.className,
props.share,
);
if (className !== 'none') {
// We found a new appearing view transition with the same name as this deletion.
viewTransitionHostInstanceIdx = 0;
const inViewport = applyViewTransitionToHostInstances(
child.child,
name,
className,
null,
false,
);
if (!inViewport) {
// This boundary is not in the viewport so we won't treat it as a matched pair.
// Revert the transition names. This avoids it flying onto the screen which can
// be disruptive and doesn't really preserve any continuity anyway.
restoreViewTransitionOnHostInstances(child.child, false);
} else {
// We'll transition between them.
const oldinstance: ViewTransitionState = child.stateNode;
const newInstance: ViewTransitionState = pair;
newInstance.paired = oldinstance;
// Note: If the other side ends up outside the viewport, we'll still run this.
// Therefore it's possible for onShare to be called with only an old snapshot.
scheduleViewTransitionEvent(child, props.onShare);
}
}
// Delete the entry so that we know when we've found all of them
// and can stop searching (size reaches zero).
pairs.delete(name);
if (pairs.size === 0) {
break;
}
}
}
}
commitDeletedPairViewTransitions(child);
}
child = child.sibling;
}
}
function commitExitViewTransitions(deletion: Fiber): void {
if (deletion.tag === ViewTransitionComponent) {
const props: ViewTransitionProps = deletion.memoizedProps;
const name = getViewTransitionName(props, deletion.stateNode);
const pair =
appearingViewTransitions !== null
? appearingViewTransitions.get(name)
: undefined;
const className: ?string = getViewTransitionClassName(
props.className,
pair !== undefined ? props.share : props.exit,
);
if (className !== 'none') {
viewTransitionHostInstanceIdx = 0;
const inViewport = applyViewTransitionToHostInstances(
deletion.child,
name,
className,
null,
false,
);
if (!inViewport) {
// Revert the transition names. This boundary is not in the viewport
// so we won't bother animating it.
restoreViewTransitionOnHostInstances(deletion.child, false);
// TODO: Should we still visit the children in case a named one was in the viewport?
} else if (pair !== undefined) {
// We found a new appearing view transition with the same name as this deletion.
// We'll transition between them instead of running the normal exit.
const oldinstance: ViewTransitionState = deletion.stateNode;
const newInstance: ViewTransitionState = pair;
newInstance.paired = oldinstance;
// Delete the entry so that we know when we've found all of them
// and can stop searching (size reaches zero).
// $FlowFixMe[incompatible-use]: Refined by the pair.
appearingViewTransitions.delete(name);
// Note: If the other side ends up outside the viewport, we'll still run this.
// Therefore it's possible for onShare to be called with only an old snapshot.
scheduleViewTransitionEvent(deletion, props.onShare);
} else {
scheduleViewTransitionEvent(deletion, props.onExit);
}
}
if (appearingViewTransitions !== null) {
// Look for more pairs deeper in the tree.
commitDeletedPairViewTransitions(deletion);
}
} else if ((deletion.subtreeFlags & ViewTransitionStatic) !== NoFlags) {
let child = deletion.child;
while (child !== null) {
commitExitViewTransitions(child);
child = child.sibling;
}
} else {
if (appearingViewTransitions !== null) {
commitDeletedPairViewTransitions(deletion);
}
}
}
function commitBeforeUpdateViewTransition(
current: Fiber,
finishedWork: Fiber,
): void {
// The way we deal with multiple HostInstances as children of a View Transition in an
// update can get tricky. The important bit is that if you swap out n HostInstances
// from n HostInstances then they match up in order. Similarly, if you don't swap
// any HostInstances each instance just transitions as is.
//
// We call this function twice. First we apply the view transition names on the
// "current" tree in the snapshot phase. Then in the mutation phase we apply view
// transition names to the "finishedWork" tree.
//
// This means that if there were insertions or deletions before an updated Instance
// that same Instance might get different names in the "old" and the "new" state.
// For example if you swap two HostInstances inside a ViewTransition they don't
// animate to swap position but rather cross-fade into the other instance. This might
// be unexpected but it is in line with the semantics that the ViewTransition is its
// own layer that cross-fades its content when it updates. If you want to reorder then
// each child needs its own ViewTransition.
const oldProps: ViewTransitionProps = current.memoizedProps;
const oldName = getViewTransitionName(oldProps, current.stateNode);
const newProps: ViewTransitionProps = finishedWork.memoizedProps;
// This className applies only if there are fewer child DOM nodes than
// before or if this update should've been cancelled but we ended up with
// a parent animating so we need to animate the child too.
// For example, if update="foo" layout="none" and it turns out this was
// a layout only change, then the "foo" class will be applied even though
// it was not actually an update. Which is a bug.
let className: ?string = getViewTransitionClassName(
newProps.className,
newProps.update,
);
if (className === 'none') {
className = getViewTransitionClassName(newProps.className, newProps.layout);
if (className === 'none') {
// If both update and layout are both "none" then we don't have to
// apply a name. Since we won't animate this boundary.
return;
}
}
viewTransitionHostInstanceIdx = 0;
applyViewTransitionToHostInstances(
current.child,
oldName,
className,
(current.memoizedState = []),
true,
);
}
function commitNestedViewTransitions(changedParent: Fiber): void {
let child = changedParent.child;
while (child !== null) {
if (child.tag === ViewTransitionComponent) {
// In this case the outer ViewTransition component wins but if there
// was an update through this component then the inner one wins.
const props: ViewTransitionProps = child.memoizedProps;
const name = getViewTransitionName(props, child.stateNode);
const className: ?string = getViewTransitionClassName(
props.className,
props.layout,
);
if (className !== 'none') {
viewTransitionHostInstanceIdx = 0;
applyViewTransitionToHostInstances(
child.child,
name,
className,
(child.memoizedState = []),
false,
);
}
} else if ((child.subtreeFlags & ViewTransitionStatic) !== NoFlags) {
commitNestedViewTransitions(child);
}
child = child.sibling;
}
}
function restorePairedViewTransitions(parent: Fiber): void {
if ((parent.subtreeFlags & ViewTransitionNamedStatic) === NoFlags) {
// This has no named view transitions in its subtree.
return;
}
let child = parent.child;
while (child !== null) {
if (child.tag === OffscreenComponent && child.memoizedState === null) {
// This tree was already hidden so we skip it.
} else {
if (
child.tag === ViewTransitionComponent &&
(child.flags & ViewTransitionNamedStatic) !== NoFlags
) {
const instance: ViewTransitionState = child.stateNode;
if (instance.paired !== null) {
instance.paired = null;
restoreViewTransitionOnHostInstances(child.child, false);
}
}
restorePairedViewTransitions(child);
}
child = child.sibling;
}
}
function restoreEnterViewTransitions(placement: Fiber): void {
if (placement.tag === ViewTransitionComponent) {
const instance: ViewTransitionState = placement.stateNode;
instance.paired = null;
restoreViewTransitionOnHostInstances(placement.child, false);
restorePairedViewTransitions(placement);
} else if ((placement.subtreeFlags & ViewTransitionStatic) !== NoFlags) {
let child = placement.child;
while (child !== null) {
restoreEnterViewTransitions(child);
child = child.sibling;
}
} else {
restorePairedViewTransitions(placement);
}
}
function restoreExitViewTransitions(deletion: Fiber): void {
if (deletion.tag === ViewTransitionComponent) {