Skip to content

Commit ddb271c

Browse files
committed
Include animated props in layout reads with the shared animated backend
With the shared animated backend, non-layout props such as transform are written to the views and to AnimatedPropsRegistry on every frame, but not committed to the shadow tree. AnimationBackendCommitHook applies the registry when React commits, so renders don't revert running animations. Layout reads from JS (measure, measureInWindow, measureLayout, getBoundingClientRect, ...) read the revision captured by LazyShadowTreeRevisionConsistencyManager though, which doesn't include these props. Pressability measures the pressable on press in, so a view moved or scaled by a native-driven animation is measured at its old position and the first move cancels the press (#51621). Behind the enableAnimatedPropsInLayoutReads flag, the revision that JS reads is cloned with the props from the registry, with the same cloning as the commit hook (moved into cloneWithAnimatedProps). The clones are only used for reads: RSNRU is suspended while cloning, so the references held by React keep pointing to committed nodes. The tree is cloned when JS reads the shadow tree (layout reads, but also DOM traversal like parentNode), not when React commits. Behind the flag, completeSurface only drops the revision captured for the surface, and the next read captures it again with the props from the registry. Capturing it in completeSurface would call AnimatedPropsRegistry::getMap before clearRegistry, which would then clear the props that the UI thread wrote after the commit hook, although they were never committed. This way, commits that are not followed by such a read also don't clone the tree. This covers C++ Animated with the shared backend only. The platform Animated modules don't write to the registry and are unchanged. One of the Fantom tests reads the layout in render and in a layout effect of the same task, so the read after the commit has to see the new commit rather than the revision captured before it. The consistency manager tests cover that invalidating makes the next read capture and transform the revision again.
1 parent ac602f7 commit ddb271c

11 files changed

Lines changed: 493 additions & 51 deletions
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @fantom_flags useSharedAnimatedBackend:true enableAnimatedPropsInLayoutReads:true updateRuntimeShadowNodeReferencesOnCommitThread:*
8+
* @flow strict-local
9+
* @format
10+
*/
11+
12+
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
13+
14+
import type {HostInstance} from 'react-native';
15+
16+
import * as ReactNativeFeatureFlags from '../../../src/private/featureflags/ReactNativeFeatureFlags';
17+
import * as Fantom from '@react-native/fantom';
18+
import nullthrows from 'nullthrows';
19+
import * as React from 'react';
20+
import {createRef, useLayoutEffect, useState} from 'react';
21+
import {Animated, Easing, View, useAnimatedValue} from 'react-native';
22+
23+
// Deferred start outputs the initial value on the first animation frame and
24+
// re-anchors timing on the second, which delays the animation by one frame.
25+
const DEFERRED_START_MS =
26+
ReactNativeFeatureFlags.animatedDeferStartOfTimingAnimations() ? 16 : 0;
27+
28+
type Layout = {pageY: number, height: number};
29+
30+
function measure(element: HostInstance): Layout {
31+
let layout: ?Layout;
32+
element.measure((x, y, width, height, pageX, pageY) => {
33+
layout = {pageY, height};
34+
});
35+
return nullthrows(layout);
36+
}
37+
38+
test('layout reads include the transform of a running native-driven animation', () => {
39+
let _translateY;
40+
const childRef = createRef<HostInstance>();
41+
42+
function MyApp() {
43+
const translateY = useAnimatedValue(0);
44+
_translateY = translateY;
45+
return (
46+
<Animated.View style={{transform: [{translateY}]}}>
47+
<View ref={childRef} style={{width: 100, height: 50}} />
48+
</Animated.View>
49+
);
50+
}
51+
52+
const root = Fantom.createRoot();
53+
54+
Fantom.runTask(() => {
55+
root.render(<MyApp />);
56+
});
57+
58+
const childElement = nullthrows(childRef.current);
59+
60+
expect(measure(childElement).pageY).toBe(0);
61+
62+
let animation;
63+
Fantom.runTask(() => {
64+
animation = Animated.timing(_translateY, {
65+
toValue: 100,
66+
duration: 1000,
67+
easing: Easing.linear,
68+
useNativeDriver: true,
69+
});
70+
animation.start();
71+
});
72+
73+
Fantom.unstable_produceFramesForDuration(500 + DEFERRED_START_MS);
74+
75+
// Nothing was committed to the shadow tree since the animation started.
76+
expect(measure(childElement).pageY).toBeCloseTo(50, 0.001);
77+
expect(measure(childElement).height).toBe(50);
78+
expect(childElement.getBoundingClientRect().y).toBeCloseTo(50, 0.001);
79+
80+
Fantom.runTask(() => {
81+
animation?.stop();
82+
});
83+
Fantom.runWorkLoop();
84+
});
85+
86+
test('layout reads include the animated props applied after a re-render', () => {
87+
let _translateY;
88+
let _setHeight;
89+
const childRef = createRef<HostInstance>();
90+
91+
function MyApp() {
92+
const translateY = useAnimatedValue(0);
93+
const [height, setHeight] = useState(50);
94+
_translateY = translateY;
95+
_setHeight = setHeight;
96+
return (
97+
<Animated.View style={{transform: [{translateY}]}}>
98+
<View ref={childRef} style={{width: 100, height}} />
99+
</Animated.View>
100+
);
101+
}
102+
103+
const root = Fantom.createRoot();
104+
105+
Fantom.runTask(() => {
106+
root.render(<MyApp />);
107+
});
108+
109+
const childElement = nullthrows(childRef.current);
110+
111+
let animation;
112+
Fantom.runTask(() => {
113+
animation = Animated.timing(_translateY, {
114+
toValue: 100,
115+
duration: 1000,
116+
easing: Easing.linear,
117+
useNativeDriver: true,
118+
});
119+
animation.start();
120+
});
121+
122+
Fantom.unstable_produceFramesForDuration(500 + DEFERRED_START_MS);
123+
124+
Fantom.runTask(() => {
125+
_setHeight(80);
126+
});
127+
128+
expect(measure(childElement).pageY).toBeCloseTo(50, 0.001);
129+
expect(measure(childElement).height).toBe(80);
130+
131+
Fantom.unstable_produceFramesForDuration(250);
132+
133+
expect(measure(childElement).pageY).toBeCloseTo(75, 0.001);
134+
135+
Fantom.runTask(() => {
136+
animation?.stop();
137+
});
138+
Fantom.runWorkLoop();
139+
});
140+
141+
test('layout reads after a commit in the same task include the commit and the animated props', () => {
142+
let _translateY;
143+
const childRef = createRef<HostInstance>();
144+
145+
function MyApp(props: {
146+
height: number,
147+
onRender?: () => void,
148+
onLayoutEffect?: () => void,
149+
}) {
150+
const {height, onRender, onLayoutEffect} = props;
151+
const translateY = useAnimatedValue(0);
152+
_translateY = translateY;
153+
onRender?.();
154+
useLayoutEffect(() => {
155+
onLayoutEffect?.();
156+
});
157+
return (
158+
<Animated.View style={{transform: [{translateY}]}}>
159+
<View ref={childRef} style={{width: 100, height}} />
160+
</Animated.View>
161+
);
162+
}
163+
164+
const root = Fantom.createRoot();
165+
166+
Fantom.runTask(() => {
167+
root.render(<MyApp height={50} />);
168+
});
169+
170+
const childElement = nullthrows(childRef.current);
171+
172+
let animation;
173+
Fantom.runTask(() => {
174+
animation = Animated.timing(_translateY, {
175+
toValue: 100,
176+
duration: 1000,
177+
easing: Easing.linear,
178+
useNativeDriver: true,
179+
});
180+
animation.start();
181+
});
182+
183+
Fantom.unstable_produceFramesForDuration(500 + DEFERRED_START_MS);
184+
185+
let layoutInRender: ?Layout;
186+
let layoutInLayoutEffect: ?Layout;
187+
Fantom.runTask(() => {
188+
root.render(
189+
<MyApp
190+
height={80}
191+
onRender={() => {
192+
layoutInRender = measure(childElement);
193+
}}
194+
onLayoutEffect={() => {
195+
layoutInLayoutEffect = measure(childElement);
196+
}}
197+
/>,
198+
);
199+
});
200+
201+
// Render and the layout effect run in the same task, so the read in render
202+
// captures the revision before the commit.
203+
expect(nullthrows(layoutInRender).height).toBe(50);
204+
expect(nullthrows(layoutInRender).pageY).toBeCloseTo(50, 0.001);
205+
expect(nullthrows(layoutInLayoutEffect).height).toBe(80);
206+
expect(nullthrows(layoutInLayoutEffect).pageY).toBeCloseTo(50, 0.001);
207+
208+
Fantom.runTask(() => {
209+
animation?.stop();
210+
});
211+
Fantom.runWorkLoop();
212+
});

‎packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.cpp‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include "AnimatedPropsRegistry.h"
1010
#include "AnimationBackendCommitHook.h"
1111

12+
#include <folly/ScopeGuard.h>
1213
#include <react/debug/react_native_assert.h>
1314
#include <react/featureflags/ReactNativeFeatureFlags.h>
1415
#include <react/renderer/animationbackend/AnimatedPropsSerializer.h>
@@ -360,4 +361,32 @@ void AnimationBackend::registerJSInvoker(
360361
}
361362
}
362363

364+
std::shared_ptr<const RootShadowNode>
365+
AnimationBackend::getRootShadowNodeWithAnimatedProps(
366+
const std::shared_ptr<const RootShadowNode>& rootShadowNode) {
367+
const auto& [families, updates] =
368+
animatedPropsRegistry_->getMap(rootShadowNode->getSurfaceId());
369+
if (families.empty()) {
370+
return rootShadowNode;
371+
}
372+
373+
// Cloning a node also clones the children that other nodes own (see
374+
// YogaLayoutableShadowNode::adoptYogaChild). These clones are never
375+
// committed, so RSNRU must not point the references held by React at them.
376+
auto useRuntimeShadowNodeReferenceUpdate =
377+
ShadowNode::getUseRuntimeShadowNodeReferenceUpdateOnThread();
378+
ShadowNode::setUseRuntimeShadowNodeReferenceUpdateOnThread(false);
379+
SCOPE_EXIT {
380+
ShadowNode::setUseRuntimeShadowNodeReferenceUpdateOnThread(
381+
useRuntimeShadowNodeReferenceUpdate);
382+
};
383+
384+
auto clonedRootShadowNode =
385+
cloneWithAnimatedProps(*rootShadowNode, families, updates);
386+
if (clonedRootShadowNode == nullptr) {
387+
return rootShadowNode;
388+
}
389+
return clonedRootShadowNode;
390+
}
391+
363392
} // namespace facebook::react

‎packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackend.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ class AnimationBackend : public UIManagerAnimationBackend {
5050
void clearRegistry(SurfaceId surfaceId) override;
5151
void clearRegistryOnSurfaceStop(SurfaceId surfaceId) override;
5252
void registerJSInvoker(std::shared_ptr<CallInvoker> jsInvoker) override;
53+
std::shared_ptr<const RootShadowNode> getRootShadowNodeWithAnimatedProps(
54+
const std::shared_ptr<const RootShadowNode> &rootShadowNode) override;
5355

5456
void onAnimationFrame(AnimationTimestamp timestamp) override;
5557
void trigger() override;

‎packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackendCommitHook.cpp‎

Lines changed: 48 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,53 @@
1111

1212
namespace facebook::react {
1313

14+
RootShadowNode::Unshared cloneWithAnimatedProps(
15+
const RootShadowNode& rootShadowNode,
16+
const std::unordered_set<std::shared_ptr<const ShadowNodeFamily>>& families,
17+
const SnapshotMap& updates) {
18+
return std::static_pointer_cast<RootShadowNode>(rootShadowNode.cloneMultiple(
19+
families,
20+
[&families, &updates](
21+
const ShadowNode& shadowNode, const ShadowNodeFragment& fragment) {
22+
auto newProps = ShadowNodeFragment::propsPlaceholder();
23+
auto children = fragment.children;
24+
std::shared_ptr<BaseViewProps> viewProps = nullptr;
25+
if (auto updatesIter = updates.find(shadowNode.getTag());
26+
updatesIter != updates.end() &&
27+
families.contains(shadowNode.getFamilyShared())) {
28+
auto& snapshot = updatesIter->second;
29+
if (!snapshot->propNames.empty() || snapshot->rawProps) {
30+
PropsParserContext propsParserContext{
31+
shadowNode.getSurfaceId(), *shadowNode.getContextContainer()};
32+
if (snapshot->rawProps) {
33+
newProps = shadowNode.getComponentDescriptor().cloneProps(
34+
propsParserContext,
35+
shadowNode.getProps(),
36+
RawProps(*snapshot->rawProps));
37+
} else {
38+
newProps = shadowNode.getComponentDescriptor().cloneProps(
39+
propsParserContext, shadowNode.getProps(), {});
40+
}
41+
viewProps = std::const_pointer_cast<BaseViewProps>(
42+
std::static_pointer_cast<const BaseViewProps>(newProps));
43+
}
44+
45+
for (const auto& propName : snapshot->propNames) {
46+
updateProp(propName, *viewProps, *snapshot);
47+
}
48+
49+
if (snapshot->text) {
50+
children = childrenWithText(shadowNode, fragment, *snapshot->text);
51+
}
52+
}
53+
return shadowNode.clone(
54+
{.props = newProps,
55+
.children = children,
56+
.state = shadowNode.getState(),
57+
.runtimeShadowNodeReference = true});
58+
}));
59+
}
60+
1461
AnimationBackendCommitHook::AnimationBackendCommitHook(
1562
UIManager& uiManager,
1663
std::shared_ptr<AnimatedPropsRegistry> animatedPropsRegistry)
@@ -37,50 +84,7 @@ RootShadowNode::Unshared AnimationBackendCommitHook::shadowTreeWillCommit(
3784
return newRootShadowNode;
3885
}
3986
auto clonedRootShadowNode =
40-
std::static_pointer_cast<RootShadowNode>(newRootShadowNode->cloneMultiple(
41-
surfaceFamilies,
42-
[&surfaceFamilies, &updates](
43-
const ShadowNode& shadowNode,
44-
const ShadowNodeFragment& fragment) {
45-
auto newProps = ShadowNodeFragment::propsPlaceholder();
46-
auto children = fragment.children;
47-
std::shared_ptr<BaseViewProps> viewProps = nullptr;
48-
if (auto updatesIter = updates.find(shadowNode.getTag());
49-
updatesIter != updates.end() &&
50-
surfaceFamilies.contains(shadowNode.getFamilyShared())) {
51-
auto& snapshot = updatesIter->second;
52-
if (!snapshot->propNames.empty() || snapshot->rawProps) {
53-
PropsParserContext propsParserContext{
54-
shadowNode.getSurfaceId(),
55-
*shadowNode.getContextContainer()};
56-
if (snapshot->rawProps) {
57-
newProps = shadowNode.getComponentDescriptor().cloneProps(
58-
propsParserContext,
59-
shadowNode.getProps(),
60-
RawProps(*snapshot->rawProps));
61-
} else {
62-
newProps = shadowNode.getComponentDescriptor().cloneProps(
63-
propsParserContext, shadowNode.getProps(), {});
64-
}
65-
viewProps = std::const_pointer_cast<BaseViewProps>(
66-
std::static_pointer_cast<const BaseViewProps>(newProps));
67-
}
68-
69-
for (const auto& propName : snapshot->propNames) {
70-
updateProp(propName, *viewProps, *snapshot);
71-
}
72-
73-
if (snapshot->text) {
74-
children =
75-
childrenWithText(shadowNode, fragment, *snapshot->text);
76-
}
77-
}
78-
return shadowNode.clone(
79-
{.props = newProps,
80-
.children = children,
81-
.state = shadowNode.getState(),
82-
.runtimeShadowNodeReference = true});
83-
}));
87+
cloneWithAnimatedProps(*newRootShadowNode, surfaceFamilies, updates);
8488

8589
if (clonedRootShadowNode == nullptr) {
8690
return newRootShadowNode;

‎packages/react-native/ReactCommon/react/renderer/animationbackend/AnimationBackendCommitHook.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,15 @@
1616

1717
namespace facebook::react {
1818

19+
/*
20+
* Clones the tree with the animated props from `updates` applied to the nodes
21+
* of `families`. Returns `nullptr` if none of the families are in the tree.
22+
*/
23+
RootShadowNode::Unshared cloneWithAnimatedProps(
24+
const RootShadowNode &rootShadowNode,
25+
const std::unordered_set<std::shared_ptr<const ShadowNodeFamily>> &families,
26+
const SnapshotMap &updates);
27+
1928
class AnimationBackendCommitHook : public UIManagerCommitHook {
2029
std::shared_ptr<AnimatedPropsRegistry> animatedPropsRegistry_;
2130

0 commit comments

Comments
 (0)