mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Fix Animated listeners on nodes derived from Animated.Value (#58037)
Summary:
Fixes https://github.com/react/react-native/issues/49719.
`addListener` stopped firing on any `AnimatedNode` *derived* from an `Animated.Value` — `Animated.add`/`subtract`/`multiply`/`divide`/`modulo`/`diffClamp` and `.interpolate()` — for natively driven animations. It worked in 0.77 and regressed in 0.78. The issue has since been reported for both `Animated.add` and `.interpolate()`, on both architectures, and the only workaround is to listen to the source value and recompute the derived value in JS — which observes intermediate values that never reach the screen.
There are two independent causes.
### 1. JS: derived nodes never subscribe to native updates
Before 38c46fe865 ("Animated: Lower `onAnimatedValueUpdate` to `AnimatedValue`", https://github.com/react/react-native/issues/48514), `AnimatedNode.addListener` called `startListeningToAnimatedNodeValue` for any node that had been made native. That commit moved the logic down into `AnimatedValue`, on the premise that:
> the `startListeningToAnimatedNodeValue` native module method only supports native tags for instances of `AnimatedValue` […] On Android, `startListeningToAnimatedNodeValue` throws if the node is not an instance of `ValueAnimatedNode`. On iOS, it does nothing if node is not an instance of `RCTValueAnimatedNode`.
That holds for props/style/transform/object/tracking/color nodes, but not for the operator and interpolation nodes, which *are* value nodes natively:
- **Android** — `AdditionAnimatedNode`, `SubtractionAnimatedNode`, `MultiplicationAnimatedNode`, `DivisionAnimatedNode`, `ModulusAnimatedNode`, `DiffClampAnimatedNode` and `InterpolationAnimatedNode` all extend `ValueAnimatedNode`, and `NativeAnimatedNodesManager` checks `node !is ValueAnimatedNode`.
- **iOS** — the corresponding `RCT*AnimatedNode` classes all inherit `RCTValueAnimatedNode`, and the manager checks `isKindOfClass:[RCTValueAnimatedNode class]`.
So the subscription was dropped for a set of nodes that natively support it. This restores it on `AnimatedNode`, gated on a new `__isNativeValueNode` flag that is `true` only for nodes backed by a native value node. That keeps the guarantee https://github.com/react/react-native/issues/48514 was after — never call `startListeningToAnimatedNodeValue` with a non-value tag — but states it explicitly instead of leaving it implicit in the class hierarchy. `AnimatedValue` now inherits that machinery rather than duplicating it.
`AnimatedNode.__detach` also drops the subscription before `dropAnimatedNode`, so it can never outlive the tag it observes.
### 2. C++: `startListeningToAnimatedNodeValue` rejects derived value nodes
Unlike Android and iOS, the C++ backend used by the New Architecture compares the node's *exact* type tag instead of testing for a `ValueAnimatedNode` subclass:
```c++
iter->second->type() == AnimatedNodeType::Value
```
so an addition or interpolation node was rejected with `"does not exist, or is not a 'value' node"`, even though `static_cast<ValueAnimatedNode*>` would have been valid. Replaced with an exhaustive `isValueNodeType` predicate, so every node type whose C++ class derives from `ValueAnimatedNode` (including `Round`) is accepted and the non-value ones are still rejected.
`AnimatedNode.__onAnimatedValueUpdateReceived` had to accept a missing `offset` as well: the C++ backend emits `onAnimatedValueUpdate` without one, which would otherwise produce `NaN` (`value + undefined`).
## Changelog:
[GENERAL] [FIXED] - `addListener` fires again for natively driven `Animated` values derived with `add`/`subtract`/`multiply`/`divide`/`modulo`/`diffClamp`/`interpolate`
Pull Request resolved: https://github.com/react/react-native/pull/58037
Test Plan:
### New tests
**`Libraries/Animated/__tests__/AnimatedComposition-itest.js`** — renders a derived node bound to `translateX`, attaches a listener to the *derived* node before it is made native, runs a `timing` animation on the source value, and asserts the listener observed the derived value; then asserts `removeListener` stops the updates. Parameterised over the five operators plus `interpolate`, and over both drivers.
**`ReactCommon/react/renderer/animated/tests/AnimatedNodeTests.cpp`** — `StartListeningToDerivedValueNode` asserts the C++ backend delivers updates for an `addition` node and stops on `stopListeningToAnimatedNodeValue`. `StartListeningToNonValueNodeIsIgnored` asserts registering on a `transform` node is still a no-op.
### Results
```
$ yarn fantom packages/react-native/Libraries/Animated/__tests__/AnimatedComposition-itest.js
addListener on derived value nodes
✓ Animated.add notifies its listeners on the JS driver
✓ Animated.subtract notifies its listeners on the JS driver
✓ Animated.multiply notifies its listeners on the JS driver
✓ Animated.divide notifies its listeners on the JS driver
✓ Animated.modulo notifies its listeners on the JS driver
✓ interpolate notifies its listeners on the JS driver
✓ Animated.add notifies its listeners on the native driver
✓ Animated.subtract notifies its listeners on the native driver
✓ Animated.multiply notifies its listeners on the native driver
✓ Animated.divide notifies its listeners on the native driver
✓ Animated.modulo notifies its listeners on the native driver
✓ interpolate notifies its listeners on the native driver
Tests: 26 passed, 26 total
```
Reverting only the fix (keeping the new test) fails exactly the six `native driver` cases, which is the reported bug; the `JS driver` cases were never broken:
```
✕ Animated.add notifies its listeners on the native driver
Expected 0 to be greater than or equal to 0
> 469 | expect(values.length).toBeGreaterThan(0);
…
Tests: 6 failed, 20 passed, 26 total
```
No regressions in the rest of the Animated suite:
```
$ yarn fantom packages/react-native/Libraries/Animated/__tests__/
Test Suites: 2 skipped, 16 passed, 16 of 18 total
Tests: 3 skipped, 297 passed, 300 total
$ yarn jest packages/react-native/Libraries/Animated
Test Suites: 3 passed, 3 total
Tests: 66 passed, 66 total
$ yarn flow-check
Found 0 errors
$ yarn lint # changed files
(no output)
```
`yarn build-types` regenerated `ReactNativeApi.d.ts`; the only substantive change is that `AnimatedValue`'s `removeListener`/`removeAllListeners` are now inherited from `AnimatedNode` rather than redeclared. `addListener` keeps its narrower `ValueListenerCallback` signature.
Correction to an earlier revision of this description: the C++ tests were not run locally, and they are not covered by the public CI either. `react/renderer/animated/tests` is excluded from the iOS build (`React-Fabric.podspec`: `ss.exclude_files = "react/renderer/animated/tests"`) and is not in the Android CMake glob (`react/renderer/animated/CMakeLists.txt` globs `*.cpp drivers/*.cpp event_drivers/*.cpp internal/*.cpp nodes/*.cpp`), so they build only in the internal build reached at import time. What is verified here: `NativeAnimatedNodesManager.cpp` compiles clean under `-Wall -Werror -Wpedantic` as part of the Fantom tester build, and the JS-side changes are covered by the Fantom and Jest runs above.
### Notes
For a colour `interpolate()` on the native driver the listener receives the interpolated colour as a number rather than a string, because the value is computed natively. That matches pre-0.78 behaviour and is out of scope here.
Reviewed By: christophpurrer, cipolleschi
Differential Revision: D117209945
Pulled By: zeyap
fbshipit-source-id: b50657a7b2d25e10e980b43cb1e9e1f1db5f3906
This commit is contained in:
1 parent
8e1559a8fb
commit
ce621bbd5b
14 files changed
+392
-98
No files matched your search
+121
@@ -379,3 +379,124 @@ describe('composition nodes: native driver, interpolation and detach', () => {
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Regression test for https://github.com/facebook/react-native/issues/49719.
|
||||
// Listeners attached to a node *derived* from an `Animated.Value` (an operator
|
||||
// or an interpolation) must keep firing, on both drivers. On the native driver
|
||||
// the value is computed natively, so the derived node has to subscribe to
|
||||
// native updates for its own tag rather than relying on the JS graph.
|
||||
describe('addListener on derived value nodes', () => {
|
||||
const derivedNodes = [
|
||||
{
|
||||
name: 'Animated.add',
|
||||
make: (base: Animated.Value) => Animated.add(base, 10),
|
||||
expected: 60,
|
||||
},
|
||||
{
|
||||
name: 'Animated.subtract',
|
||||
make: (base: Animated.Value) => Animated.subtract(base, 10),
|
||||
expected: 40,
|
||||
},
|
||||
{
|
||||
name: 'Animated.multiply',
|
||||
make: (base: Animated.Value) => Animated.multiply(base, 2),
|
||||
expected: 100,
|
||||
},
|
||||
{
|
||||
name: 'Animated.divide',
|
||||
make: (base: Animated.Value) => Animated.divide(base, 2),
|
||||
expected: 25,
|
||||
},
|
||||
{
|
||||
name: 'Animated.modulo',
|
||||
make: (base: Animated.Value) => Animated.modulo(base, 7),
|
||||
expected: 50 % 7,
|
||||
},
|
||||
{
|
||||
// Accumulates the delta of its input and clamps it: as `base` climbs
|
||||
// from 0 to 50 the accumulated delta saturates at `max`.
|
||||
name: 'Animated.diffClamp',
|
||||
make: (base: Animated.Value) => Animated.diffClamp(base, 0, 20),
|
||||
expected: 20,
|
||||
},
|
||||
{
|
||||
name: 'interpolate',
|
||||
make: (base: Animated.Value) =>
|
||||
base.interpolate({inputRange: [0, 50], outputRange: [0, 500]}),
|
||||
expected: 500,
|
||||
},
|
||||
];
|
||||
|
||||
for (const useNativeDriver of [false, true]) {
|
||||
const driverName = useNativeDriver ? 'native driver' : 'JS driver';
|
||||
|
||||
for (const {name, make, expected} of derivedNodes) {
|
||||
it(`${name} notifies its listeners on the ${driverName}`, () => {
|
||||
let base: ?Animated.Value;
|
||||
let node: ?Animated.Node;
|
||||
|
||||
function MyApp() {
|
||||
const value = useAnimatedValue(0);
|
||||
base = value;
|
||||
node = make(value);
|
||||
return (
|
||||
<Animated.View
|
||||
style={[
|
||||
{width: 100, height: 100},
|
||||
{transform: [{translateX: node}]},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const root = Fantom.createRoot();
|
||||
Fantom.runTask(() => {
|
||||
root.render(<MyApp />);
|
||||
});
|
||||
|
||||
// The listener is attached before the node is made native, so this
|
||||
// also covers the subscription being created from `__makeNative`. The
|
||||
// opposite order — attaching once the node is already native — is
|
||||
// covered per node type by AnimatedNative-test.
|
||||
const values: Array<number> = [];
|
||||
const listenerId = nullthrows(node).addListener(state => {
|
||||
values.push(state.value);
|
||||
});
|
||||
|
||||
let animation: ?Animated.CompositeAnimation;
|
||||
Fantom.runTask(() => {
|
||||
animation = Animated.timing(nullthrows(base), {
|
||||
toValue: 50,
|
||||
duration: 100,
|
||||
useNativeDriver,
|
||||
});
|
||||
animation.start();
|
||||
});
|
||||
Fantom.unstable_produceFramesForDuration(200);
|
||||
Fantom.runWorkLoop();
|
||||
|
||||
expect(values.length).toBeGreaterThan(0);
|
||||
expect(values[values.length - 1]).toBeCloseTo(expected, 0);
|
||||
|
||||
// Removing the listener stops the updates.
|
||||
nullthrows(node).removeListener(listenerId);
|
||||
const countAfterRemoval = values.length;
|
||||
Fantom.runTask(() => {
|
||||
nullthrows(base).setValue(0);
|
||||
});
|
||||
Fantom.unstable_produceFramesForDuration(32);
|
||||
Fantom.runWorkLoop();
|
||||
expect(values.length).toBe(countAfterRemoval);
|
||||
|
||||
Fantom.runTask(() => {
|
||||
nullthrows(animation).stop();
|
||||
});
|
||||
Fantom.runTask(() => {
|
||||
root.render(<Animated.View style={{width: 1, height: 1}} />);
|
||||
});
|
||||
Fantom.unstable_produceFramesForDuration(16);
|
||||
Fantom.runWorkLoop();
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -20,6 +20,8 @@ import AnimatedValue from './AnimatedValue';
|
||||
import AnimatedWithChildren from './AnimatedWithChildren';
|
||||
|
||||
export default class AnimatedAddition extends AnimatedWithChildren {
|
||||
__isNativeValueNode: boolean = true;
|
||||
|
||||
_a: AnimatedNode;
|
||||
_b: AnimatedNode;
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ import AnimatedInterpolation from './AnimatedInterpolation';
|
||||
import AnimatedWithChildren from './AnimatedWithChildren';
|
||||
|
||||
export default class AnimatedDiffClamp extends AnimatedWithChildren {
|
||||
__isNativeValueNode: boolean = true;
|
||||
|
||||
_a: AnimatedNode;
|
||||
_min: number;
|
||||
_max: number;
|
||||
|
||||
@@ -20,6 +20,8 @@ import AnimatedValue from './AnimatedValue';
|
||||
import AnimatedWithChildren from './AnimatedWithChildren';
|
||||
|
||||
export default class AnimatedDivision extends AnimatedWithChildren {
|
||||
__isNativeValueNode: boolean = true;
|
||||
|
||||
_a: AnimatedNode;
|
||||
_b: AnimatedNode;
|
||||
_warnedAboutDivideByZero: boolean = false;
|
||||
|
||||
@@ -444,6 +444,8 @@ function sampleEasingStops(
|
||||
export default class AnimatedInterpolation<
|
||||
OutputT extends InterpolationConfigSupportedOutputType,
|
||||
> extends AnimatedWithChildren {
|
||||
__isNativeValueNode: boolean = true;
|
||||
|
||||
_parent: AnimatedNode;
|
||||
_config: InterpolationConfigType<OutputT>;
|
||||
_interpolation: ?(input: number) => OutputT;
|
||||
|
||||
@@ -19,6 +19,8 @@ import AnimatedInterpolation from './AnimatedInterpolation';
|
||||
import AnimatedWithChildren from './AnimatedWithChildren';
|
||||
|
||||
export default class AnimatedModulo extends AnimatedWithChildren {
|
||||
__isNativeValueNode: boolean = true;
|
||||
|
||||
_a: AnimatedNode;
|
||||
_modulus: number;
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ import AnimatedValue from './AnimatedValue';
|
||||
import AnimatedWithChildren from './AnimatedWithChildren';
|
||||
|
||||
export default class AnimatedMultiplication extends AnimatedWithChildren {
|
||||
__isNativeValueNode: boolean = true;
|
||||
|
||||
_a: AnimatedNode;
|
||||
_b: AnimatedNode;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
import type {EventSubscription} from '../../vendor/emitter/EventEmitter';
|
||||
import type {PlatformConfig} from '../AnimatedPlatformConfig';
|
||||
|
||||
import NativeAnimatedHelper from '../../../src/private/animated/NativeAnimatedHelper';
|
||||
@@ -54,7 +55,12 @@ export default class AnimatedNode {
|
||||
this.removeAllListeners();
|
||||
}
|
||||
if (this.__isNative && this.__nativeTag != null) {
|
||||
NativeAnimatedHelper.API.dropAnimatedNode(this.__nativeTag);
|
||||
const nativeTag = this.__nativeTag;
|
||||
// The subscription must not outlive the native tag it observes. Any
|
||||
// listeners kept around are re-subscribed by `__makeNative` if this node
|
||||
// is attached again.
|
||||
this.__updateSubscription?.remove();
|
||||
NativeAnimatedHelper.API.dropAnimatedNode(nativeTag);
|
||||
this.__nativeTag = undefined;
|
||||
}
|
||||
}
|
||||
@@ -73,6 +79,19 @@ export default class AnimatedNode {
|
||||
__nativeTag: ?number = undefined;
|
||||
__disableBatchingForNativeCreate: ?boolean = undefined;
|
||||
|
||||
/**
|
||||
* Whether the native node backing this one holds a number, and therefore
|
||||
* supports `startListeningToAnimatedNodeValue`. That native module method
|
||||
* only accepts tags of "value" nodes (`ValueAnimatedNode` on Android and in
|
||||
* C++, `RCTValueAnimatedNode` on iOS); passing any other tag throws on
|
||||
* Android and is a no-op elsewhere.
|
||||
*
|
||||
* Subclasses backed by a non-value native node — props, style, transform,
|
||||
* object, tracking and color — must leave this `false`.
|
||||
*/
|
||||
__isNativeValueNode: boolean = false;
|
||||
__updateSubscription: ?EventSubscription = null;
|
||||
|
||||
__makeNative(platformConfig: ?PlatformConfig): void {
|
||||
// Subclasses are expected to set `__isNative` to true before this.
|
||||
invariant(
|
||||
@@ -81,6 +100,9 @@ export default class AnimatedNode {
|
||||
);
|
||||
|
||||
this._platformConfig = platformConfig;
|
||||
if (this._listeners.size > 0) {
|
||||
this.__ensureUpdateSubscriptionExists();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,6 +115,9 @@ export default class AnimatedNode {
|
||||
addListener(callback: (value: any) => unknown): string {
|
||||
const id = String(_uniqueId++);
|
||||
this._listeners.set(id, callback);
|
||||
if (this.__isNative) {
|
||||
this.__ensureUpdateSubscriptionExists();
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -104,6 +129,9 @@ export default class AnimatedNode {
|
||||
*/
|
||||
removeListener(id: string): void {
|
||||
this._listeners.delete(id);
|
||||
if (this.__isNative && this._listeners.size === 0) {
|
||||
this.__updateSubscription?.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,14 +141,53 @@ export default class AnimatedNode {
|
||||
*/
|
||||
removeAllListeners(): void {
|
||||
this._listeners.clear();
|
||||
if (this.__isNative) {
|
||||
this.__updateSubscription?.remove();
|
||||
}
|
||||
}
|
||||
|
||||
hasListeners(): boolean {
|
||||
return this._listeners.size > 0;
|
||||
}
|
||||
|
||||
__onAnimatedValueUpdateReceived(value: number, offset: number): void {
|
||||
this.__callListeners(value + offset);
|
||||
/**
|
||||
* Subscribes to native updates of this node's value, so that listeners keep
|
||||
* firing for natively driven animations. No-op for nodes that are not backed
|
||||
* by a native "value" node.
|
||||
*/
|
||||
__ensureUpdateSubscriptionExists(): void {
|
||||
if (!this.__isNativeValueNode || this.__updateSubscription != null) {
|
||||
return;
|
||||
}
|
||||
const nativeTag = this.__getNativeTag();
|
||||
NativeAnimatedHelper.API.startListeningToAnimatedNodeValue(nativeTag);
|
||||
const subscription: EventSubscription =
|
||||
NativeAnimatedHelper.nativeEventEmitter.addListener(
|
||||
'onAnimatedValueUpdate',
|
||||
data => {
|
||||
if (data.tag === nativeTag) {
|
||||
this.__onAnimatedValueUpdateReceived(data.value, data.offset);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
this.__updateSubscription = {
|
||||
remove: () => {
|
||||
// Only this function assigns to `this.__updateSubscription`.
|
||||
if (this.__updateSubscription == null) {
|
||||
return;
|
||||
}
|
||||
this.__updateSubscription = null;
|
||||
subscription.remove();
|
||||
NativeAnimatedHelper.API.stopListeningToAnimatedNodeValue(nativeTag);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// NOTE: only Android sends an `offset`; iOS and the C++ backend omit it and
|
||||
// report a value that already accounts for one.
|
||||
__onAnimatedValueUpdateReceived(value: number, offset?: ?number): void {
|
||||
this.__callListeners(value + (offset ?? 0));
|
||||
}
|
||||
|
||||
__callListeners(value: number): void {
|
||||
|
||||
@@ -20,6 +20,8 @@ import AnimatedValue from './AnimatedValue';
|
||||
import AnimatedWithChildren from './AnimatedWithChildren';
|
||||
|
||||
export default class AnimatedSubtraction extends AnimatedWithChildren {
|
||||
__isNativeValueNode: boolean = true;
|
||||
|
||||
_a: AnimatedNode;
|
||||
_b: AnimatedNode;
|
||||
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
* @format
|
||||
*/
|
||||
|
||||
import type {EventSubscription} from '../../vendor/emitter/EventEmitter';
|
||||
import type {PlatformConfig} from '../AnimatedPlatformConfig';
|
||||
import type Animation from '../animations/Animation';
|
||||
import type {EndCallback} from '../animations/Animation';
|
||||
import type {
|
||||
@@ -88,8 +86,7 @@ function _executeAsAnimatedBatch(id: string, operation: () => void) {
|
||||
* See https://reactnative.dev/docs/animatedvalue
|
||||
*/
|
||||
export default class AnimatedValue extends AnimatedWithChildren {
|
||||
_listenerCount: number;
|
||||
_updateSubscription: ?EventSubscription;
|
||||
__isNativeValueNode: boolean = true;
|
||||
|
||||
_value: number;
|
||||
_startingValue: number;
|
||||
@@ -104,9 +101,6 @@ export default class AnimatedValue extends AnimatedWithChildren {
|
||||
throw new Error('AnimatedValue: Attempting to set value to undefined');
|
||||
}
|
||||
|
||||
this._listenerCount = 0;
|
||||
this._updateSubscription = null;
|
||||
|
||||
this._startingValue = this._value = value;
|
||||
this._offset = 0;
|
||||
this.__deferAnimationStart =
|
||||
@@ -124,9 +118,6 @@ export default class AnimatedValue extends AnimatedWithChildren {
|
||||
});
|
||||
}
|
||||
this.stopAnimation();
|
||||
if (ReactNativeFeatureFlags.animatedKeepListenersOnDetach()) {
|
||||
this._updateSubscription?.remove();
|
||||
}
|
||||
super.__detach();
|
||||
}
|
||||
|
||||
@@ -134,65 +125,12 @@ export default class AnimatedValue extends AnimatedWithChildren {
|
||||
return this._value + this._offset;
|
||||
}
|
||||
|
||||
__makeNative(platformConfig: ?PlatformConfig): void {
|
||||
super.__makeNative(platformConfig);
|
||||
if (this._listenerCount > 0) {
|
||||
this.__ensureUpdateSubscriptionExists();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrows `AnimatedNode.addListener`: the value of an `Animated.Value` is
|
||||
* always a number, so listeners always receive `{value: number}`.
|
||||
*/
|
||||
addListener(callback: ValueListenerCallback): string {
|
||||
const id = super.addListener(callback);
|
||||
this._listenerCount++;
|
||||
if (this.__isNative) {
|
||||
this.__ensureUpdateSubscriptionExists();
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
removeListener(id: string): void {
|
||||
super.removeListener(id);
|
||||
this._listenerCount--;
|
||||
if (this.__isNative && this._listenerCount === 0) {
|
||||
this._updateSubscription?.remove();
|
||||
}
|
||||
}
|
||||
|
||||
removeAllListeners(): void {
|
||||
super.removeAllListeners();
|
||||
this._listenerCount = 0;
|
||||
if (this.__isNative) {
|
||||
this._updateSubscription?.remove();
|
||||
}
|
||||
}
|
||||
|
||||
__ensureUpdateSubscriptionExists(): void {
|
||||
if (this._updateSubscription != null) {
|
||||
return;
|
||||
}
|
||||
const nativeTag = this.__getNativeTag();
|
||||
NativeAnimatedAPI.startListeningToAnimatedNodeValue(nativeTag);
|
||||
const subscription: EventSubscription =
|
||||
NativeAnimatedHelper.nativeEventEmitter.addListener(
|
||||
'onAnimatedValueUpdate',
|
||||
data => {
|
||||
if (data.tag === nativeTag) {
|
||||
this.__onAnimatedValueUpdateReceived(data.value, data.offset);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
this._updateSubscription = {
|
||||
remove: () => {
|
||||
// Only this function assigns to `this.#updateSubscription`.
|
||||
if (this._updateSubscription == null) {
|
||||
return;
|
||||
}
|
||||
this._updateSubscription = null;
|
||||
subscription.remove();
|
||||
NativeAnimatedAPI.stopListeningToAnimatedNodeValue(nativeTag);
|
||||
},
|
||||
};
|
||||
return super.addListener(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -297,7 +235,7 @@ export default class AnimatedValue extends AnimatedWithChildren {
|
||||
}
|
||||
}
|
||||
|
||||
__onAnimatedValueUpdateReceived(value: number, offset?: number): void {
|
||||
__onAnimatedValueUpdateReceived(value: number, offset?: ?number): void {
|
||||
this._updateValue(value, false /*flush*/);
|
||||
if (offset != null) {
|
||||
this._offset = offset;
|
||||
|
||||
+31
-4
@@ -51,6 +51,33 @@ struct NodesQueueItem {
|
||||
bool connectedToFinishedAnimation;
|
||||
};
|
||||
|
||||
// Whether `type` is backed by a `ValueAnimatedNode` subclass, i.e. whether the
|
||||
// node holds a number that can be observed. Kept exhaustive (no `default`) so
|
||||
// that adding a node type is a compile error until it is classified here.
|
||||
bool isValueNodeType(AnimatedNodeType type) noexcept {
|
||||
switch (type) {
|
||||
case AnimatedNodeType::Value:
|
||||
case AnimatedNodeType::Interpolation:
|
||||
case AnimatedNodeType::Addition:
|
||||
case AnimatedNodeType::Subtraction:
|
||||
case AnimatedNodeType::Division:
|
||||
case AnimatedNodeType::Multiplication:
|
||||
case AnimatedNodeType::Modulus:
|
||||
case AnimatedNodeType::Diffclamp:
|
||||
case AnimatedNodeType::Round:
|
||||
return true;
|
||||
case AnimatedNodeType::Style:
|
||||
case AnimatedNodeType::Props:
|
||||
case AnimatedNodeType::Transform:
|
||||
case AnimatedNodeType::Tracking:
|
||||
case AnimatedNodeType::Color:
|
||||
case AnimatedNodeType::Object:
|
||||
return false;
|
||||
}
|
||||
// Unreachable: the switch above is exhaustive.
|
||||
return false;
|
||||
}
|
||||
|
||||
void mergeObjects(folly::dynamic& out, const folly::dynamic& objectToMerge) {
|
||||
react_native_assert(objectToMerge.isObject());
|
||||
if (out.isObject() && !out.empty()) {
|
||||
@@ -921,8 +948,8 @@ void NativeAnimatedNodesManager::resolvePlatformColor(
|
||||
void NativeAnimatedNodesManager::startListeningToAnimatedNodeValue(
|
||||
Tag tag,
|
||||
ValueListenerCallback&& callback) noexcept {
|
||||
if (auto iter = animatedNodes_.find(tag); iter != animatedNodes_.end() &&
|
||||
iter->second->type() == AnimatedNodeType::Value) {
|
||||
if (auto iter = animatedNodes_.find(tag);
|
||||
iter != animatedNodes_.end() && isValueNodeType(iter->second->type())) {
|
||||
static_cast<ValueAnimatedNode*>(iter->second.get())
|
||||
->setValueListener(std::move(callback));
|
||||
} else {
|
||||
@@ -933,8 +960,8 @@ void NativeAnimatedNodesManager::startListeningToAnimatedNodeValue(
|
||||
|
||||
void NativeAnimatedNodesManager::stopListeningToAnimatedNodeValue(
|
||||
Tag tag) noexcept {
|
||||
if (auto iter = animatedNodes_.find(tag); iter != animatedNodes_.end() &&
|
||||
iter->second->type() == AnimatedNodeType::Value) {
|
||||
if (auto iter = animatedNodes_.find(tag);
|
||||
iter != animatedNodes_.end() && isValueNodeType(iter->second->type())) {
|
||||
static_cast<ValueAnimatedNode*>(iter->second.get())
|
||||
->setValueListener(nullptr);
|
||||
} else {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <react/renderer/animated/nodes/ObjectAnimatedNode.h>
|
||||
#include <react/renderer/core/ReactRootViewTagGenerator.h>
|
||||
#include <react/renderer/graphics/Color.h>
|
||||
#include <vector>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
@@ -254,6 +255,85 @@ TEST_F(AnimatedNodeTests, RoundAnimatedNodeUsesNearestConfigKey) {
|
||||
EXPECT_DOUBLE_EQ(nodesManager_->getValue(roundTag).value(), 15.0);
|
||||
}
|
||||
|
||||
TEST_F(AnimatedNodeTests, StartListeningToDerivedValueNode) {
|
||||
// Every node that derives from ValueAnimatedNode holds an observable number,
|
||||
// so `startListeningToAnimatedNodeValue` must accept it — not only nodes of
|
||||
// type "value". See https://github.com/facebook/react-native/issues/49719.
|
||||
initNodesManager();
|
||||
|
||||
auto rootTag = getNextRootViewTag();
|
||||
|
||||
auto valueTag = ++rootTag;
|
||||
auto addendTag = ++rootTag;
|
||||
auto additionTag = ++rootTag;
|
||||
|
||||
nodesManager_->createAnimatedNode(
|
||||
valueTag,
|
||||
folly::dynamic::object("type", "value")("value", 0)("offset", 0));
|
||||
nodesManager_->createAnimatedNode(
|
||||
addendTag,
|
||||
folly::dynamic::object("type", "value")("value", 10)("offset", 0));
|
||||
nodesManager_->createAnimatedNode(
|
||||
additionTag,
|
||||
folly::dynamic::object("type", "addition")(
|
||||
"input", folly::dynamic::array(valueTag, addendTag)));
|
||||
nodesManager_->connectAnimatedNodes(valueTag, additionTag);
|
||||
nodesManager_->connectAnimatedNodes(addendTag, additionTag);
|
||||
|
||||
std::vector<double> observedValues;
|
||||
nodesManager_->startListeningToAnimatedNodeValue(
|
||||
additionTag,
|
||||
[&observedValues](double value) { observedValues.push_back(value); });
|
||||
|
||||
runAnimationFrame(0);
|
||||
|
||||
nodesManager_->setAnimatedNodeValue(valueTag, 32);
|
||||
runAnimationFrame(0);
|
||||
|
||||
ASSERT_FALSE(observedValues.empty());
|
||||
EXPECT_DOUBLE_EQ(observedValues.back(), 42);
|
||||
|
||||
nodesManager_->stopListeningToAnimatedNodeValue(additionTag);
|
||||
|
||||
const auto countAfterStop = observedValues.size();
|
||||
nodesManager_->setAnimatedNodeValue(valueTag, 0);
|
||||
runAnimationFrame(0);
|
||||
|
||||
EXPECT_EQ(observedValues.size(), countAfterStop);
|
||||
}
|
||||
|
||||
TEST_F(AnimatedNodeTests, StartListeningToNonValueNodeIsIgnored) {
|
||||
// Nodes that do not hold a number cannot be observed. Registering a listener
|
||||
// on one must be a no-op rather than an unchecked cast.
|
||||
initNodesManager();
|
||||
|
||||
auto rootTag = getNextRootViewTag();
|
||||
|
||||
auto valueTag = ++rootTag;
|
||||
auto transformTag = ++rootTag;
|
||||
|
||||
nodesManager_->createAnimatedNode(
|
||||
valueTag,
|
||||
folly::dynamic::object("type", "value")("value", 1)("offset", 0));
|
||||
nodesManager_->createAnimatedNode(
|
||||
transformTag,
|
||||
folly::dynamic::object("type", "transform")(
|
||||
"transforms",
|
||||
folly::dynamic::array(
|
||||
folly::dynamic::object("type", "animated")(
|
||||
"property", "translateX")("nodeTag", valueTag))));
|
||||
nodesManager_->connectAnimatedNodes(valueTag, transformTag);
|
||||
|
||||
bool called = false;
|
||||
nodesManager_->startListeningToAnimatedNodeValue(
|
||||
transformTag, [&called](double /*value*/) { called = true; });
|
||||
|
||||
nodesManager_->setAnimatedNodeValue(valueTag, 5);
|
||||
runAnimationFrame(0);
|
||||
|
||||
EXPECT_FALSE(called);
|
||||
}
|
||||
|
||||
TEST_F(AnimatedNodeTests, SetOffsetReturnsFalseWhenUnchanged) {
|
||||
// This test verifies that setAnimatedNodeOffset doesn't trigger unnecessary
|
||||
// updates when the offset value hasn't changed.
|
||||
|
||||
+20
-22
@@ -4,7 +4,7 @@
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @generated SignedSource<<0cdd169a97730ccd6c6fdb359f0eb30d>>
|
||||
* @generated SignedSource<<5391dae1ee6f722cdac0c6590bd19a44>>
|
||||
*
|
||||
* This file was generated by scripts/js-api/build-types/index.js.
|
||||
*/
|
||||
@@ -1412,8 +1412,6 @@ declare class AnimatedValue_default extends AnimatedWithChildren_default {
|
||||
interpolate<OutputT extends InterpolationConfigSupportedOutputType>(
|
||||
config: InterpolationConfigType<OutputT>,
|
||||
): AnimatedInterpolation_default<OutputT>
|
||||
removeAllListeners(): void
|
||||
removeListener(id: string): void
|
||||
resetAnimation(callback?: ((value: number) => void) | null | undefined): void
|
||||
setOffset(offset: number): void
|
||||
setValue(value: number): void
|
||||
@@ -5758,7 +5756,7 @@ export {
|
||||
AlertOptions, // 8a116d2a
|
||||
AlertType, // 5ab91217
|
||||
AndroidKeyboardEvent, // e03becc8
|
||||
Animated, // e99db73c
|
||||
Animated, // b73ca27a
|
||||
AppConfig, // 35c0ca70
|
||||
AppRegistry, // 5bc2bced
|
||||
AppState, // 12012be5
|
||||
@@ -5772,8 +5770,8 @@ export {
|
||||
BackPressEventName, // 4620fb76
|
||||
BlurEvent, // 4ba4f941
|
||||
BoxShadowValue, // b679703f
|
||||
Button, // 78a75446
|
||||
ButtonInstance, // aecdca9d
|
||||
Button, // 1618c5dc
|
||||
ButtonInstance, // b62f6c43
|
||||
ButtonProps, // 21c5780c
|
||||
Clipboard, // 41addb89
|
||||
CodegenTypes, // ab4986cc
|
||||
@@ -5810,9 +5808,9 @@ export {
|
||||
EventSubscription, // b8d084aa
|
||||
ExtendedExceptionData, // 5a6ccf5a
|
||||
FilterFunction, // bf24c0e3
|
||||
FlatList, // ff6fd4b9
|
||||
FlatListInstance, // 930e6e0d
|
||||
FlatListProps, // b77a3695
|
||||
FlatList, // 31e4dbb8
|
||||
FlatListInstance, // e256df59
|
||||
FlatListProps, // d134a60c
|
||||
FocusEvent, // 850f1517
|
||||
FontVariant, // 7c7558bb
|
||||
GestureResponderEvent, // 14d3e77a
|
||||
@@ -5953,18 +5951,18 @@ export {
|
||||
ScrollEvent, // d7abdd0a
|
||||
ScrollResponderType, // 4fb54e25
|
||||
ScrollToLocationParamsType, // d7ecdad1
|
||||
ScrollView, // 5b9149bf
|
||||
ScrollView, // 74f481ff
|
||||
ScrollViewImperativeMethods, // 308dd401
|
||||
ScrollViewInstance, // b86e49e8
|
||||
ScrollViewProps, // 40e3563d
|
||||
ScrollViewProps, // 3bcd863e
|
||||
ScrollViewPropsAndroid, // 02f3df2e
|
||||
ScrollViewPropsIOS, // 807cb4f6
|
||||
ScrollViewScrollToOptions, // 3313411e
|
||||
SectionBase, // 9f13db00
|
||||
SectionList, // 5ad78704
|
||||
SectionList, // f7750d02
|
||||
SectionListData, // 1a4de01a
|
||||
SectionListInstance, // ce15f61c
|
||||
SectionListProps, // 3b9f4d91
|
||||
SectionListInstance, // 6f7c0fa0
|
||||
SectionListProps, // d1569771
|
||||
SectionListRenderItem, // 715b2086
|
||||
SectionListRenderItemInfo, // 4a48a922
|
||||
Separators, // 6a45f7e3
|
||||
@@ -5981,7 +5979,7 @@ export {
|
||||
StatusBarProps, // c2a44d88
|
||||
StatusBarStyle, // 78f53eea
|
||||
StyleProp, // fa0e9b4a
|
||||
StyleSheet, // f7fe407a
|
||||
StyleSheet, // e2400c9e
|
||||
SubmitBehavior, // c4ddf490
|
||||
Switch, // cf0d6ce5
|
||||
SwitchChangeEvent, // 899635b1
|
||||
@@ -6017,9 +6015,9 @@ export {
|
||||
TouchableNativeFeedback, // e2791ad5
|
||||
TouchableNativeFeedbackInstance, // ce1ad7e9
|
||||
TouchableNativeFeedbackProps, // ffc9c1d4
|
||||
TouchableOpacity, // fac1cc91
|
||||
TouchableOpacity, // 46c89652
|
||||
TouchableOpacityInstance, // b186055b
|
||||
TouchableOpacityProps, // 9e3eeec9
|
||||
TouchableOpacityProps, // d7c93220
|
||||
TouchableWithoutFeedback, // da544b16
|
||||
TouchableWithoutFeedbackProps, // a14626e7
|
||||
TransformsStyle, // 65e70f18
|
||||
@@ -6037,10 +6035,10 @@ export {
|
||||
VirtualViewMode, // 6be59722
|
||||
VirtualizedList, // 68c7345e
|
||||
VirtualizedListInstance, // 423ee7c0
|
||||
VirtualizedListProps, // 5dded4a1
|
||||
VirtualizedListProps, // 89659fe0
|
||||
VirtualizedSectionList, // 9fd9cd61
|
||||
VirtualizedSectionListInstance, // 12b706d5
|
||||
VirtualizedSectionListProps, // ef311473
|
||||
VirtualizedSectionListProps, // 52c34787
|
||||
WrapperComponentProvider, // 9ef54e61
|
||||
codegenNativeCommands, // 628a7c0a
|
||||
codegenNativeComponent, // 520daa94
|
||||
@@ -6048,9 +6046,9 @@ export {
|
||||
processColor, // 6e877698
|
||||
registerCallableModule, // 839c8cfe
|
||||
requireNativeComponent, // aa36a6dd
|
||||
useAnimatedColor, // 31a919f9
|
||||
useAnimatedValue, // 3eb9d3c0
|
||||
useAnimatedValueXY, // b434ca0f
|
||||
useAnimatedColor, // 821ed7dc
|
||||
useAnimatedValue, // d625d6a9
|
||||
useAnimatedValueXY, // a4c13498
|
||||
useColorScheme, // d585efdb
|
||||
usePressability, // 782138ed
|
||||
useWindowDimensions, // bb4b683f
|
||||
|
||||
@@ -348,6 +348,55 @@ describe('Native Animated', () => {
|
||||
expect(listener).toBeCalledWith({value: 42});
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('subscribes to native updates for nodes derived from a value', () => {
|
||||
const {Animated} = importModules();
|
||||
|
||||
const base = new Animated.Value(0);
|
||||
// Every operator and interpolation node is backed by a native value
|
||||
// node, so each must subscribe for its own tag rather than relying on
|
||||
// the JS graph, which native updates bypass. Listening starts here from
|
||||
// an already-native node, exercising the `__isNative` branch of
|
||||
// `addListener`; AnimatedComposition-itest covers the `__makeNative`
|
||||
// one, where the listener predates the node going native.
|
||||
const derived = [
|
||||
Animated.add(base, 10),
|
||||
Animated.subtract(base, 10),
|
||||
Animated.multiply(base, 2),
|
||||
Animated.divide(base, 2),
|
||||
Animated.modulo(base, 7),
|
||||
Animated.diffClamp(base, 0, 20),
|
||||
base.interpolate({inputRange: [0, 1], outputRange: [0, 1]}),
|
||||
];
|
||||
|
||||
for (const node of derived) {
|
||||
node.__makeNative();
|
||||
node.addListener(jest.fn());
|
||||
expect(
|
||||
NativeAnimatedModule.startListeningToAnimatedNodeValue,
|
||||
).toHaveBeenCalledWith(node.__getNativeTag());
|
||||
}
|
||||
|
||||
expect(
|
||||
NativeAnimatedModule.startListeningToAnimatedNodeValue,
|
||||
).toHaveBeenCalledTimes(derived.length);
|
||||
});
|
||||
|
||||
it('never subscribes to native updates for a non-value node', () => {
|
||||
const {Animated} = importModules();
|
||||
|
||||
// `startListeningToAnimatedNodeValue` throws on Android for any tag that
|
||||
// is not backed by a `ValueAnimatedNode`, so nodes that do not hold a
|
||||
// number must never reach it. `Animated.Color` is the only such node
|
||||
// that is publicly constructible.
|
||||
const color = new Animated.Color('red');
|
||||
color.__makeNative();
|
||||
color.addListener(jest.fn());
|
||||
|
||||
expect(
|
||||
NativeAnimatedModule.startListeningToAnimatedNodeValue,
|
||||
).not.toHaveBeenCalledWith(color.__getNativeTag());
|
||||
});
|
||||
});
|
||||
|
||||
describe('Animated Events', () => {
|
||||
|
||||
Reference in new issue
Block a user