Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Animated: Store Listeners w/ Map #46372

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,21 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall react_native
*/

import Animated from '../Animated';
import AnimatedObject, {hasAnimatedNode} from '../nodes/AnimatedObject';
import nullthrows from 'nullthrows';

describe('AnimatedObject', () => {
let Animated;
let AnimatedObject;

beforeEach(() => {
jest.resetModules();

Animated = require('../Animated').default;
AnimatedObject = require('../nodes/AnimatedObject').default;
});

it('should get the proper value', () => {
Expand All @@ -24,15 +28,17 @@ describe('AnimatedObject', () => {
outputRange: [100, 200],
});

const node = new AnimatedObject([
{
translate: [translateAnim, translateAnim],
},
{
translateX: translateAnim,
},
{scale: anim},
]);
const node = nullthrows(
AnimatedObject.from([
{
translate: [translateAnim, translateAnim],
},
{
translateX: translateAnim,
},
{scale: anim},
]),
);

expect(node.__getValue()).toEqual([
{translate: [100, 100]},
Expand All @@ -48,15 +54,17 @@ describe('AnimatedObject', () => {
outputRange: [100, 200],
});

const node = new AnimatedObject([
{
translate: [translateAnim, translateAnim],
},
{
translateX: translateAnim,
},
{scale: anim},
]);
const node = nullthrows(
AnimatedObject.from([
{
translate: [translateAnim, translateAnim],
},
{
translateX: translateAnim,
},
{scale: anim},
]),
);

node.__makeNative();

Expand All @@ -65,26 +73,24 @@ describe('AnimatedObject', () => {
expect(translateAnim.__isNative).toBe(true);
});

describe('hasAnimatedNode', () => {
it('should detect any animated nodes', () => {
expect(hasAnimatedNode(10)).toBe(false);
it('detects animated nodes', () => {
expect(AnimatedObject.from(10)).toBe(null);

const anim = new Animated.Value(0);
expect(hasAnimatedNode(anim)).toBe(true);
const anim = new Animated.Value(0);
expect(AnimatedObject.from(anim)).not.toBe(null);

const event = Animated.event([{}], {useNativeDriver: true});
expect(hasAnimatedNode(event)).toBe(false);
const event = Animated.event([{}], {useNativeDriver: true});
expect(AnimatedObject.from(event)).toBe(null);

expect(hasAnimatedNode([10, 10])).toBe(false);
expect(hasAnimatedNode([10, anim])).toBe(true);
expect(AnimatedObject.from([10, 10])).toBe(null);
expect(AnimatedObject.from([10, anim])).not.toBe(null);

expect(hasAnimatedNode({a: 10, b: 10})).toBe(false);
expect(hasAnimatedNode({a: 10, b: anim})).toBe(true);
expect(AnimatedObject.from({a: 10, b: 10})).toBe(null);
expect(AnimatedObject.from({a: 10, b: anim})).not.toBe(null);

expect(hasAnimatedNode({a: 10, b: {ba: 10, bb: 10}})).toBe(false);
expect(hasAnimatedNode({a: 10, b: {ba: 10, bb: anim}})).toBe(true);
expect(hasAnimatedNode({a: 10, b: [10, 10]})).toBe(false);
expect(hasAnimatedNode({a: 10, b: [10, anim]})).toBe(true);
});
expect(AnimatedObject.from({a: 10, b: {ba: 10, bb: 10}})).toBe(null);
expect(AnimatedObject.from({a: 10, b: {ba: 10, bb: anim}})).not.toBe(null);
expect(AnimatedObject.from({a: 10, b: [10, 10]})).toBe(null);
expect(AnimatedObject.from({a: 10, b: [10, anim]})).not.toBe(null);
});
});
73 changes: 41 additions & 32 deletions packages/react-native/Libraries/Animated/nodes/AnimatedNode.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,31 @@

'use strict';

import type {EventSubscription} from '../../vendor/emitter/EventEmitter';
import type {PlatformConfig} from '../AnimatedPlatformConfig';

import NativeAnimatedHelper from '../../../src/private/animated/NativeAnimatedHelper';
import invariant from 'invariant';

const NativeAnimatedAPI = NativeAnimatedHelper.API;
const {startListeningToAnimatedNodeValue, stopListeningToAnimatedNodeValue} =
NativeAnimatedHelper.API;

type ValueListenerCallback = (state: {value: number, ...}) => mixed;

let _uniqueId = 1;
let _assertNativeAnimatedModule: ?() => void = () => {
NativeAnimatedHelper.assertNativeAnimatedModule();
// We only have to assert that the module exists once. After we've asserted
// this, clear out the function so we know to skip it in the future.
_assertNativeAnimatedModule = null;
};

// Note(vjeux): this would be better as an interface but flow doesn't
// support them yet
export default class AnimatedNode {
_listeners: {[key: string]: ValueListenerCallback, ...};
_platformConfig: ?PlatformConfig;
__nativeAnimatedValueListener: ?any;
#listeners: Map<string, ValueListenerCallback> = new Map();
_platformConfig: ?PlatformConfig = undefined;
__nativeAnimatedValueListener: ?EventSubscription = null;
__attach(): void {}
__detach(): void {
this.removeAllListeners();
Expand All @@ -46,21 +54,17 @@ export default class AnimatedNode {
}

/* Methods and props used by native Animated impl */
__isNative: boolean;
__nativeTag: ?number;
__shouldUpdateListenersForNewNativeTag: boolean;

constructor() {
this._listeners = {};
}
__isNative: boolean = false;
__nativeTag: ?number = undefined;
__shouldUpdateListenersForNewNativeTag: boolean = false;

__makeNative(platformConfig: ?PlatformConfig): void {
if (!this.__isNative) {
throw new Error('This node cannot be made a "native" animated node');
}

this._platformConfig = platformConfig;
if (this.hasListeners()) {
if (this.#listeners.size > 0) {
this._startListeningToNativeValueUpdates();
}
}
Expand All @@ -74,7 +78,7 @@ export default class AnimatedNode {
*/
addListener(callback: (value: any) => mixed): string {
const id = String(_uniqueId++);
this._listeners[id] = callback;
this.#listeners.set(id, callback);
if (this.__isNative) {
this._startListeningToNativeValueUpdates();
}
Expand All @@ -88,8 +92,8 @@ export default class AnimatedNode {
* See https://reactnative.dev/docs/animatedvalue#removelistener
*/
removeListener(id: string): void {
delete this._listeners[id];
if (this.__isNative && !this.hasListeners()) {
this.#listeners.delete(id);
if (this.__isNative && this.#listeners.size === 0) {
this._stopListeningForNativeValueUpdates();
}
}
Expand All @@ -100,14 +104,14 @@ export default class AnimatedNode {
* See https://reactnative.dev/docs/animatedvalue#removealllisteners
*/
removeAllListeners(): void {
this._listeners = {};
this.#listeners.clear();
if (this.__isNative) {
this._stopListeningForNativeValueUpdates();
}
}

hasListeners(): boolean {
return !!Object.keys(this._listeners).length;
return this.#listeners.size > 0;
}

_startListeningToNativeValueUpdates() {
Expand All @@ -123,7 +127,7 @@ export default class AnimatedNode {
this._stopListeningForNativeValueUpdates();
}

NativeAnimatedAPI.startListeningToAnimatedNodeValue(this.__getNativeTag());
startListeningToAnimatedNodeValue(this.__getNativeTag());
this.__nativeAnimatedValueListener =
NativeAnimatedHelper.nativeEventEmitter.addListener(
'onAnimatedValueUpdate',
Expand All @@ -141,9 +145,10 @@ export default class AnimatedNode {
}

__callListeners(value: number): void {
for (const key in this._listeners) {
this._listeners[key]({value});
}
const event = {value};
this.#listeners.forEach(listener => {
listener(event);
});
}

_stopListeningForNativeValueUpdates() {
Expand All @@ -153,31 +158,34 @@ export default class AnimatedNode {

this.__nativeAnimatedValueListener.remove();
this.__nativeAnimatedValueListener = null;
NativeAnimatedAPI.stopListeningToAnimatedNodeValue(this.__getNativeTag());
stopListeningToAnimatedNodeValue(this.__getNativeTag());
}

__getNativeTag(): number {
NativeAnimatedHelper.assertNativeAnimatedModule();
invariant(
this.__isNative,
'Attempt to get native tag from node not marked as "native"',
);

const nativeTag =
this.__nativeTag ?? NativeAnimatedHelper.generateNewNodeTag();
let nativeTag = this.__nativeTag;
if (nativeTag == null) {
_assertNativeAnimatedModule?.();

// `__isNative` is initialized as false and only ever set to true. So we
// only need to check it once here when initializing `__nativeTag`.
invariant(
this.__isNative,
'Attempt to get native tag from node not marked as "native"',
);

if (this.__nativeTag == null) {
nativeTag = NativeAnimatedHelper.generateNewNodeTag();
this.__nativeTag = nativeTag;

const config = this.__getNativeConfig();
if (this._platformConfig) {
config.platformConfig = this._platformConfig;
}
NativeAnimatedHelper.API.createAnimatedNode(nativeTag, config);
this.__shouldUpdateListenersForNewNativeTag = true;
}

return nativeTag;
}

__getNativeConfig(): Object {
throw new Error(
'This JS animated node type cannot be used as native animated node',
Expand All @@ -191,6 +199,7 @@ export default class AnimatedNode {
__getPlatformConfig(): ?PlatformConfig {
return this._platformConfig;
}

__setPlatformConfig(platformConfig: ?PlatformConfig) {
this._platformConfig = platformConfig;
}
Expand Down
Loading
Loading