diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedModule.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedModule.cpp new file mode 100644 index 00000000000..599a7df743a --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedModule.cpp @@ -0,0 +1,267 @@ +/* + * 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. + */ + +#include "AnimatedModule.h" + +#include +#include + +namespace facebook::react { + +AnimatedModule::AnimatedModule( + std::shared_ptr jsInvoker, + std::shared_ptr nodesManagerProvider) + : NativeAnimatedModuleCxxSpec(jsInvoker), + nodesManagerProvider_(std::move(nodesManagerProvider)) {} + +void AnimatedModule::startOperationBatch(jsi::Runtime& /*rt*/) {} + +void AnimatedModule::finishOperationBatch(jsi::Runtime& /*rt*/) { + // No mutex needed, operations only added via TurboModule method invocation + std::vector preOperations; + std::vector operations; + std::swap(preOperations_, preOperations); + std::swap(operations_, operations); + scheduleOperationOnUI([preOperations = std::move(preOperations), + operations = std::move(operations)]( + NativeAnimatedNodesManager& nodesManager) { + for (auto& preOperation : preOperations) { + preOperation(nodesManager); + } + + for (auto& operation : operations) { + operation(nodesManager); + } + }); +} + +void AnimatedModule::createAnimatedNode( + jsi::Runtime& rt, + Tag tag, + jsi::Object config) { + auto configDynamic = dynamicFromValue(rt, jsi::Value(rt, config)); + addOperation([tag, configDynamic = std::move(configDynamic)]( + NativeAnimatedNodesManager& nodesManager) { + nodesManager.createAnimatedNode(tag, configDynamic); + }); +} + +void AnimatedModule::updateAnimatedNodeConfig( + jsi::Runtime& rt, + Tag tag, + jsi::Object config) { + auto configDynamic = dynamicFromValue(rt, jsi::Value(rt, config)); + addOperation([tag, configDynamic = std::move(configDynamic)]( + NativeAnimatedNodesManager& nodesManager) { + nodesManager.updateAnimatedNodeConfig(tag, configDynamic); + }); +} + +void AnimatedModule::getValue( + jsi::Runtime& /*rt*/, + Tag tag, + const AsyncCallback& saveValueCallback) { + addOperation([tag, + saveValueCallback, + weakJsInvoker = std::weak_ptr(jsInvoker_)]( + NativeAnimatedNodesManager& nodesManager) { + auto animValue = nodesManager.getValue(tag); + auto jsInvoker = weakJsInvoker.lock(); + if (animValue && jsInvoker) { + jsInvoker->invokeAsync( + [animValue, saveValueCallback = saveValueCallback]() { + saveValueCallback.call(animValue.value()); + }); + }; + }); +} + +void AnimatedModule::startListeningToAnimatedNodeValue( + jsi::Runtime& /*rt*/, + Tag tag) { + addOperation([tag, weakThis = weak_from_this()]( + NativeAnimatedNodesManager& nodesManager) { + nodesManager.startListeningToAnimatedNodeValue( + tag, [weakThis, tag](double value) { + if (auto strongThis = weakThis.lock()) { + strongThis->emitDeviceEvent( + "onAnimatedValueUpdate", + [tag, value](jsi::Runtime& rt, std::vector& args) { + auto arg = jsi::Object(rt); + arg.setProperty(rt, "tag", jsi::Value(tag)); + arg.setProperty(rt, "value", jsi::Value(value)); + args.emplace_back(rt, arg); + }); + } + }); + }); +} + +void AnimatedModule::stopListeningToAnimatedNodeValue( + jsi::Runtime& /*rt*/, + Tag tag) { + addOperation([tag](NativeAnimatedNodesManager& nodesManager) { + nodesManager.stopListeningToAnimatedNodeValue(tag); + }); +} + +void AnimatedModule::connectAnimatedNodes( + jsi::Runtime& /*rt*/, + Tag parentTag, + Tag childTag) { + addOperation([parentTag, childTag](NativeAnimatedNodesManager& nodesManager) { + nodesManager.connectAnimatedNodes(parentTag, childTag); + }); +} + +void AnimatedModule::disconnectAnimatedNodes( + jsi::Runtime& /*rt*/, + Tag parentTag, + Tag childTag) { + addOperation([parentTag, childTag](NativeAnimatedNodesManager& nodesManager) { + nodesManager.disconnectAnimatedNodes(parentTag, childTag); + }); +} + +void AnimatedModule::startAnimatingNode( + jsi::Runtime& rt, + int animationId, + Tag nodeTag, + jsi::Object config, + AnimationEndCallback endCallback) { + auto configDynamic = dynamicFromValue(rt, jsi::Value(rt, config)); + addOperation([animationId, + nodeTag, + configDynamic = std::move(configDynamic), + endCallback = std::move(endCallback)]( + NativeAnimatedNodesManager& nodesManager) { + nodesManager.startAnimatingNode( + animationId, nodeTag, configDynamic, endCallback); + }); +} + +void AnimatedModule::stopAnimation(jsi::Runtime& /*rt*/, int animationId) { + addOperation([animationId](NativeAnimatedNodesManager& nodesManager) { + nodesManager.stopAnimation( + animationId, false /* TODO: isTrackingAnimation */); + }); +} + +void AnimatedModule::setAnimatedNodeValue( + jsi::Runtime& /*rt*/, + Tag nodeTag, + double value) { + addOperation([nodeTag, value](NativeAnimatedNodesManager& nodesManager) { + nodesManager.setAnimatedNodeValue(nodeTag, value); + }); +} + +void AnimatedModule::setAnimatedNodeOffset( + jsi::Runtime& /*rt*/, + Tag nodeTag, + double offset) { + addOperation([nodeTag, offset](NativeAnimatedNodesManager& nodesManager) { + nodesManager.setAnimatedNodeOffset(nodeTag, offset); + }); +} + +void AnimatedModule::flattenAnimatedNodeOffset( + jsi::Runtime& /*rt*/, + Tag nodeTag) { + addOperation([nodeTag](NativeAnimatedNodesManager& nodesManager) { + nodesManager.flattenAnimatedNodeOffset(nodeTag); + }); +} + +void AnimatedModule::extractAnimatedNodeOffset( + jsi::Runtime& /*rt*/, + Tag nodeTag) { + addOperation([nodeTag](NativeAnimatedNodesManager& nodesManager) { + nodesManager.extractAnimatedNodeOffset(nodeTag); + }); +} + +void AnimatedModule::connectAnimatedNodeToView( + jsi::Runtime& /*rt*/, + Tag nodeTag, + Tag viewTag) { + addOperation([nodeTag, viewTag](NativeAnimatedNodesManager& nodesManager) { + nodesManager.connectAnimatedNodeToView(nodeTag, viewTag); + }); +} + +void AnimatedModule::disconnectAnimatedNodeFromView( + jsi::Runtime& /*rt*/, + Tag nodeTag, + Tag viewTag) { + addOperation([nodeTag, viewTag](NativeAnimatedNodesManager& nodesManager) { + nodesManager.disconnectAnimatedNodeFromView(nodeTag, viewTag); + }); +} + +void AnimatedModule::restoreDefaultValues(jsi::Runtime& /*rt*/, Tag nodeTag) { + addOperation( + [nodeTag](NativeAnimatedNodesManager& nodesManager) { + nodesManager.restoreDefaultValues(nodeTag); + }, + /* preOperation = */ true); +} + +void AnimatedModule::dropAnimatedNode(jsi::Runtime& /*rt*/, Tag tag) { + addOperation([tag](NativeAnimatedNodesManager& nodesManager) { + nodesManager.dropAnimatedNode(tag); + }); +} + +void AnimatedModule::addAnimatedEventToView( + jsi::Runtime& rt, + Tag viewTag, + const std::string& eventName, + jsi::Object eventMapping) { + auto eventMappingDynamic = dynamicFromValue(rt, jsi::Value(rt, eventMapping)); + addOperation([viewTag, eventName, eventMappingDynamic]( + NativeAnimatedNodesManager& nodesManager) { + nodesManager.addAnimatedEventToView( + viewTag, eventName, eventMappingDynamic); + }); +} + +void AnimatedModule::removeAnimatedEventFromView( + jsi::Runtime& /*rt*/, + Tag viewTag, + const std::string& eventName, + Tag animatedNodeTag) { + addOperation([viewTag, eventName, animatedNodeTag]( + NativeAnimatedNodesManager& nodesManager) { + nodesManager.removeAnimatedEventFromView( + viewTag, eventName, animatedNodeTag); + }); +} + +void AnimatedModule::addListener( + jsi::Runtime& rt, + const std::string& eventName) {} + +void AnimatedModule::removeListeners(jsi::Runtime& rt, int count) {} + +void AnimatedModule::queueAndExecuteBatchedOperations( + jsi::Runtime& rt, + jsi::Array operationsAndArgs) {} + +void AnimatedModule::addOperation(Operation&& operation, bool preOperation) { + // No mutex needed, operations only added via TurboModule method invocation + auto& queue = preOperation ? preOperations_ : operations_; + queue.push_back(std::move(operation)); +} + +void AnimatedModule::installJSIBindingsWithRuntime(jsi::Runtime& runtime) { + if (nodesManagerProvider_) { + nodesManager_ = nodesManagerProvider_->getOrCreate(runtime); + } +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedModule.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedModule.h new file mode 100644 index 00000000000..906c1e04145 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedModule.h @@ -0,0 +1,124 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +class AnimatedModule : public NativeAnimatedModuleCxxSpec, + public std::enable_shared_from_this, + public TurboModuleWithJSIBindings { + using Operation = + std::function; + + public: + AnimatedModule( + std::shared_ptr jsInvoker, + std::shared_ptr nodesManagerProvider); + + void startOperationBatch(jsi::Runtime& rt); + + void finishOperationBatch(jsi::Runtime& rt); + + void createAnimatedNode(jsi::Runtime& rt, Tag tag, jsi::Object config); + + void updateAnimatedNodeConfig(jsi::Runtime& rt, Tag tag, jsi::Object config); + + void getValue( + jsi::Runtime& rt, + Tag tag, + const AsyncCallback& saveValueCallback); + + void startListeningToAnimatedNodeValue(jsi::Runtime& rt, Tag tag); + + void stopListeningToAnimatedNodeValue(jsi::Runtime& rt, Tag tag); + + void connectAnimatedNodes(jsi::Runtime& rt, Tag parentTag, Tag childTag); + + void disconnectAnimatedNodes(jsi::Runtime& rt, Tag parentTag, Tag childTag); + + void startAnimatingNode( + jsi::Runtime& rt, + int animationId, + Tag nodeTag, + jsi::Object config, + AnimationEndCallback endCallback); + + void stopAnimation(jsi::Runtime& rt, int animationId); + + void setAnimatedNodeValue(jsi::Runtime& rt, Tag nodeTag, double value); + + void setAnimatedNodeOffset(jsi::Runtime& rt, Tag nodeTag, double offset); + + void flattenAnimatedNodeOffset(jsi::Runtime& rt, Tag nodeTag); + + void extractAnimatedNodeOffset(jsi::Runtime& rt, Tag nodeTag); + + void connectAnimatedNodeToView(jsi::Runtime& rt, Tag nodeTag, Tag viewTag); + + void + disconnectAnimatedNodeFromView(jsi::Runtime& rt, Tag nodeTag, Tag viewTag); + + void restoreDefaultValues(jsi::Runtime& rt, Tag nodeTag); + + void dropAnimatedNode(jsi::Runtime& rt, Tag tag); + + void addAnimatedEventToView( + jsi::Runtime& rt, + Tag viewTag, + const std::string& eventName, + jsi::Object eventMapping); + + void removeAnimatedEventFromView( + jsi::Runtime& rt, + Tag viewTag, + const std::string& eventName, + Tag animatedNodeTag); + + void addListener(jsi::Runtime& rt, const std::string& eventName); + + void removeListeners(jsi::Runtime& rt, int count); + + void queueAndExecuteBatchedOperations( + jsi::Runtime& rt, + jsi::Array operationsAndArgs); + + void scheduleOperationOnUI(Operation&& fn) { + if (nodesManager_) { + nodesManager_->scheduleOnUI( + [fn = std::move(fn), + weakNodesManager = + std::weak_ptr(nodesManager_)]() { + if (auto nodesManager = weakNodesManager.lock()) { + fn(*nodesManager); + } + }); + } + } + + protected: + std::shared_ptr nodesManagerProvider_; + + private: + std::shared_ptr nodesManager_; + std::vector preOperations_; + std::vector operations_; + + void addOperation(Operation&& operation, bool preOperation = false); + + void installJSIBindingsWithRuntime(jsi::Runtime& runtime) override; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedMountingOverrideDelegate.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedMountingOverrideDelegate.cpp new file mode 100644 index 00000000000..f3aaf751787 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedMountingOverrideDelegate.cpp @@ -0,0 +1,93 @@ +/* + * 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. + */ + +#include "AnimatedMountingOverrideDelegate.h" + +#include +#include +#include + +namespace facebook::react { + +AnimatedMountingOverrideDelegate::AnimatedMountingOverrideDelegate( + std::function(Tag)> getAnimatedManagedProps, + std::weak_ptr uiManagerBinding) + : MountingOverrideDelegate(), + getAnimatedManagedProps_(std::move(getAnimatedManagedProps)), + uiManagerBinding_(std::move(uiManagerBinding)){}; + +bool AnimatedMountingOverrideDelegate::shouldOverridePullTransaction() const { + return getAnimatedManagedProps_ != nullptr; +} + +std::optional +AnimatedMountingOverrideDelegate::pullTransaction( + SurfaceId surfaceId, + MountingTransaction::Number transactionNumber, + const TransactionTelemetry& telemetry, + ShadowViewMutationList mutations) const { + if (!getAnimatedManagedProps_) { + return MountingTransaction{ + surfaceId, transactionNumber, std::move(mutations), telemetry}; + } + + std::unordered_map animatedManagedProps; + for (const auto& mutation : mutations) { + if (mutation.type == ShadowViewMutation::Update) { + const auto tag = mutation.newChildShadowView.tag; + if (auto props = getAnimatedManagedProps_(tag)) { + animatedManagedProps.insert({tag, std::move(*props)}); + } + } + } + + if (animatedManagedProps.empty()) { + return MountingTransaction{ + surfaceId, transactionNumber, std::move(mutations), telemetry}; + } + + ShadowViewMutation::List filteredMutations; + for (const auto& mutation : mutations) { + folly::dynamic modifiedProps = folly::dynamic::object(); + if (mutation.type == ShadowViewMutation::Update) { + if (auto node = + animatedManagedProps.extract(mutation.newChildShadowView.tag)) { + modifiedProps = std::move(node.mapped()); + } + } + if (modifiedProps.empty()) { + filteredMutations.emplace_back(mutation); + } else { + if (auto uiManagerBinding = uiManagerBinding_.lock()) { + auto* scheduler = static_cast( + uiManagerBinding->getUIManager().getDelegate()); + react_native_assert(scheduler); + if (const auto* componentDescriptor = + scheduler + ->findComponentDescriptorByHandle_DO_NOT_USE_THIS_IS_BROKEN( + mutation.newChildShadowView.componentHandle)) { + PropsParserContext propsParserContext{ + mutation.newChildShadowView.surfaceId, + *scheduler->getContextContainer()}; + auto modifiedNewChildShadowView = mutation.newChildShadowView; + modifiedNewChildShadowView.props = componentDescriptor->cloneProps( + propsParserContext, + mutation.newChildShadowView.props, + RawProps(std::move(modifiedProps))); + filteredMutations.emplace_back(ShadowViewMutation::UpdateMutation( + mutation.oldChildShadowView, + std::move(modifiedNewChildShadowView), + mutation.parentTag)); + } + } + } + } + return MountingTransaction{ + surfaceId, transactionNumber, std::move(filteredMutations), telemetry}; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedMountingOverrideDelegate.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedMountingOverrideDelegate.h new file mode 100644 index 00000000000..d9914b2ca9f --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/AnimatedMountingOverrideDelegate.h @@ -0,0 +1,42 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +class UIManagerBinding; + +class AnimatedMountingOverrideDelegate : public MountingOverrideDelegate { + public: + AnimatedMountingOverrideDelegate( + std::function(Tag)> getAnimatedManagedProps, + std::weak_ptr uiManagerBinding); + + bool shouldOverridePullTransaction() const override; + + std::optional pullTransaction( + SurfaceId surfaceId, + MountingTransaction::Number transactionNumber, + const TransactionTelemetry& telemetry, + ShadowViewMutationList mutations) const override; + + private: + std::function(Tag)> getAnimatedManagedProps_; + + std::weak_ptr uiManagerBinding_; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/EventEmitterListener.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/EventEmitterListener.h new file mode 100644 index 00000000000..ce526ec39c7 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/EventEmitterListener.h @@ -0,0 +1,72 @@ +/* + * 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. + */ + +#pragma once + +#include +#include + +#include +#include + +namespace facebook::react { + +/** + * Listener for events dispatched to JS runtime. + * Return `true` to interrupt default dispatch to JS event emitter, `false` to + * pass through to default handlers. + */ + +template +using EventListenerT = std::function; + +template +class EventListenerContainerT { + public: + /* + * Invoke listeners in this container with the event. + * Returns true if event was handled by the listener, false to continue + * default dispatch. + */ + bool willDispatchEvent(TArgs... args) { + std::shared_lock lock(mutex_); + bool handled = false; + for (const auto& listener : eventListeners_) { + handled = (*listener)(args...); + if (handled) { + break; + } + } + return handled; + } + + void addListener(std::shared_ptr> listener) { + std::unique_lock lock(mutex_); + eventListeners_.push_back(std::move(listener)); + } + + void removeListener( + const std::shared_ptr>& listener) { + std::unique_lock lock(mutex_); + auto it = + std::find(eventListeners_.begin(), eventListeners_.end(), listener); + if (it != eventListeners_.end()) { + eventListeners_.erase(it); + } + } + + private: + std::shared_mutex mutex_; + std::vector>> eventListeners_; +}; + +using EventEmitterListener = + EventListenerT; +using EventEmitterListenerContainer = + EventListenerContainerT; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedAllowlist.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedAllowlist.h new file mode 100644 index 00000000000..a1769d7c617 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedAllowlist.h @@ -0,0 +1,63 @@ +/* + * 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. + */ + +#pragma once + +#include +#include + +namespace facebook::react { + +inline static std::unordered_set getDirectManipulationAllowlist() { + /** + * Direct manipulation eligible styles allowed by the NativeAnimated JS + * implementation. Keep in sync with + * packages/react-native/Libraries/Animated/NativeAnimatedAllowlist.js + */ + static std::unordered_set DIRECT_MANIPULATION_STYLES{ + /* SUPPORTED_COLOR_STYLES */ + "backgroundColor", + "borderBottomColor", + "borderColor", + "borderEndColor", + "borderLeftColor", + "borderRightColor", + "borderStartColor", + "borderTopColor", + "color", + "tintColor", + + /* SUPPORTED STYLES */ + "borderBottomEndRadius", + "borderBottomLeftRadius", + "borderBottomRightRadius", + "borderBottomStartRadius", + "borderEndEndRadius", + "borderEndStartRadius", + "borderRadius", + "borderTopEndRadius", + "borderTopLeftRadius", + "borderTopRightRadius", + "borderTopStartRadius", + "borderStartEndRadius", + "borderStartStartRadius", + "elevation", + "opacity", + "transform", + "zIndex", + /* ios styles */ + "shadowOpacity", + "shadowRadius", + /* legacy android transform properties */ + "scaleX", + "scaleY", + "translateX", + "translateY", + }; + return DIRECT_MANIPULATION_STYLES; +} +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManager.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManager.cpp new file mode 100644 index 00000000000..676eafa218c --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManager.cpp @@ -0,0 +1,804 @@ +/* + * 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. + */ + +#include "NativeAnimatedNodesManager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +namespace { + +struct NodesQueueItem { + std::shared_ptr node; + bool connectedToFinishedAnimation; +}; + +void mergeObjects(folly::dynamic& out, const folly::dynamic& objectToMerge) { + react_native_assert(objectToMerge.isObject()); + if (out.isObject() && !out.empty()) { + for (const auto& pair : objectToMerge.items()) { + out[pair.first] = pair.second; + } + } else { + out = objectToMerge; + } +} + +} // namespace + +NativeAnimatedNodesManager::NativeAnimatedNodesManager( + DirectManipulationCallback&& directManipulationCallback, + FabricCommitCallback&& fabricCommitCallback, + StartOnRenderCallback&& startOnRenderCallback, + StopOnRenderCallback&& stopOnRenderCallback) noexcept + : directManipulationCallback_(std::move(directManipulationCallback)), + fabricCommitCallback_(std::move(fabricCommitCallback)), + startOnRenderCallback_(std::move(startOnRenderCallback)), + stopOnRenderCallback_(std::move(stopOnRenderCallback)) {} + +std::optional NativeAnimatedNodesManager::getValue(Tag tag) { + auto node = getAnimatedNode(tag); + if (node) { + return node->value(); + } else { + LOG(WARNING) + << "Cannot get value from AnimatedNode, it's not a ValueAnimatedNode"; + return std::nullopt; + } +} + +// graph + +std::unique_ptr NativeAnimatedNodesManager::animatedNode( + Tag tag, + const folly::dynamic& config) { + auto typeName = config["type"].asString(); + + auto type = AnimatedNode::getNodeTypeByName(typeName); + if (!type) { + LOG(WARNING) << "Invalid AnimatedNode type " << typeName; + return nullptr; + } + + switch (type.value()) { + case AnimatedNodeType::Style: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Value: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Color: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Props: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Tracking: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Interpolation: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Transform: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Subtraction: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Addition: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Multiplication: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Division: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Modulus: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Diffclamp: + return std::make_unique( + tag, config, shared_from_this()); + case AnimatedNodeType::Round: + return std::make_unique( + tag, config, shared_from_this()); + default: + LOG(WARNING) << "Cannot create AnimatedNode of type " << typeName + << ", it's not implemented yet"; + return nullptr; + } +} + +void NativeAnimatedNodesManager::createAnimatedNode( + Tag tag, + const folly::dynamic& config) { + auto node = animatedNode(tag, config); + if (node) { + std::lock_guard lock(connectedAnimatedNodesMutex_); + animatedNodes_.emplace(tag, std::move(node)); + updatedNodeTags_.insert(tag); + } +} + +void NativeAnimatedNodesManager::connectAnimatedNodes( + Tag parentTag, + Tag childTag) { + react_native_assert(parentTag); + react_native_assert(childTag); + + auto parentNode = getAnimatedNode(parentTag); + auto childNode = getAnimatedNode(childTag); + + if (parentNode && childNode) { + parentNode->addChild(childTag); + updatedNodeTags_.insert(childTag); + } else { + LOG(WARNING) << "Cannot ConnectAnimatedNodes, parentTag = " << parentTag + << ", childTag = " << childTag + << ", not all of them are created"; + } +} + +void NativeAnimatedNodesManager::connectAnimatedNodeToView( + Tag propsNodeTag, + Tag viewTag) { + react_native_assert(propsNodeTag); + react_native_assert(viewTag); + + auto node = getAnimatedNode(propsNodeTag); + if (node) { + node->connectToView(viewTag); + { + std::lock_guard lock(connectedAnimatedNodesMutex_); + connectedAnimatedNodes_.insert({viewTag, propsNodeTag}); + } + updatedNodeTags_.insert(node->tag()); + } else { + LOG(WARNING) + << "Cannot ConnectAnimatedNodeToView, animated node has to be props type"; + } +} + +void NativeAnimatedNodesManager::disconnectAnimatedNodeFromView( + Tag propsNodeTag, + Tag viewTag) { + react_native_assert(propsNodeTag); + react_native_assert(viewTag); + + auto node = getAnimatedNode(propsNodeTag); + if (node) { + node->disconnectFromView(viewTag); + { + std::lock_guard lock(connectedAnimatedNodesMutex_); + connectedAnimatedNodes_.erase(viewTag); + } + updatedNodeTags_.insert(node->tag()); + } else { + LOG(WARNING) + << "Cannot DisconnectAnimatedNodeToView, animated node has to be props type"; + } +} + +void NativeAnimatedNodesManager::disconnectAnimatedNodes( + Tag parentTag, + Tag childTag) { + react_native_assert(parentTag); + react_native_assert(childTag); + + auto parentNode = getAnimatedNode(parentTag); + auto childNode = getAnimatedNode(childTag); + + if (parentNode && childNode) { + parentNode->removeChild(childTag); + } else { + LOG(WARNING) << "Cannot DisconnectAnimatedNodes, parentTag = " << parentTag + << ", childTag = " << childTag + << ", not all of them are created"; + } +} + +void NativeAnimatedNodesManager::restoreDefaultValues(Tag tag) { + if (auto propsNode = getAnimatedNode(tag)) { + propsNode->restoreDefaultValues(); + } +} + +void NativeAnimatedNodesManager::dropAnimatedNode(Tag tag) { + std::lock_guard lock(connectedAnimatedNodesMutex_); + animatedNodes_.erase(tag); +} + +// mutations + +void NativeAnimatedNodesManager::setAnimatedNodeValue(Tag tag, double value) { + if (auto node = getAnimatedNode(tag)) { + stopAnimationsForNode(node->tag()); + if (node->setRawValue(value)) { + updatedNodeTags_.insert(node->tag()); + } + } +} + +void NativeAnimatedNodesManager::stopAnimationsForNode(Tag nodeTag) { + std::vector discardedAnimIds{}; + + for (const auto& [animationId, driver] : activeAnimations_) { + if (driver->animatedValueTag() == nodeTag) { + discardedAnimIds.emplace_back(animationId); + } + } + for (const auto& id : discardedAnimIds) { + activeAnimations_.at(id)->stopAnimation(); + activeAnimations_.erase(id); + } +} + +void NativeAnimatedNodesManager::setAnimatedNodeOffset( + Tag /*tag*/, + double /*offset*/) { + LOG(WARNING) << "SetAnimatedNodeOffset is unimplemented"; +} + +void NativeAnimatedNodesManager::flattenAnimatedNodeOffset(Tag /*tag*/) { + LOG(WARNING) << "FlattenAnimatedNodeOffset is unimplemented"; +} + +void NativeAnimatedNodesManager::extractAnimatedNodeOffset(Tag /*tag*/) { + LOG(WARNING) << "ExtractAnimatedNodeOffset is unimplemented"; +} + +void NativeAnimatedNodesManager::updateAnimatedNodeConfig( + Tag /*tag*/, + const folly::dynamic& /*config*/) { + LOG(WARNING) << "UpdateAnimatedNodeConfig is unimplemented"; +} + +// drivers + +void NativeAnimatedNodesManager::startAnimatingNode( + int animationId, + Tag animatedNodeTag, + const folly::dynamic& config, + const std::optional& endCallback) { + if (auto iter = activeAnimations_.find(animationId); + iter != activeAnimations_.end()) { + // reset animation config + auto animation = iter->second; + animation->updateConfig(config); + } else if (animatedNodes_.contains(animatedNodeTag)) { + auto type = config["type"].asString(); + auto typeEnum = AnimationDriver::getDriverTypeByName(type); + std::shared_ptr animation = nullptr; + if (typeEnum) { + switch (typeEnum.value()) { + case AnimationDriverType::Frames: { + animation = std::make_shared( + animationId, animatedNodeTag, endCallback, config, this); + } break; + case AnimationDriverType::Spring: { + animation = std::make_shared( + animationId, animatedNodeTag, endCallback, config, this); + } break; + case AnimationDriverType::Decay: { + animation = std::make_shared( + animationId, animatedNodeTag, endCallback, config, this); + } break; + } + if (animation) { + activeAnimations_.insert({animationId, animation}); + animation->startAnimation(); + } + } else { + LOG(ERROR) << "Unknown AnimationDriver type " << type; + } + } +} + +void NativeAnimatedNodesManager::stopAnimation( + int animationId, + bool /*isTrackingAnimation*/) { + if (auto iter = activeAnimations_.find(animationId); + iter != activeAnimations_.end()) { + iter->second->stopAnimation(); + activeAnimations_.erase(iter); + } +} + +void NativeAnimatedNodesManager::addAnimatedEventToView( + Tag viewTag, + const std::string& eventName, + const folly::dynamic& eventMapping) { + const auto animatedValueTag = (eventMapping.count("animatedValueTag") != 0u) + ? static_cast(eventMapping["animatedValueTag"].asInt()) + : 0; + const auto& pathList = eventMapping["nativeEventPath"]; + auto numPaths = pathList.size(); + std::vector eventPath(numPaths); + for (size_t i = 0; i < numPaths; i++) { + eventPath[i] = pathList[i].asString(); + } + + const auto key = EventAnimationDriverKey{ + viewTag, EventEmitter::normalizeEventType(eventName)}; + if (auto driversIter = eventDrivers_.find(key); + driversIter != eventDrivers_.end()) { + auto& drivers = driversIter->second; + drivers.emplace_back( + std::make_unique(eventPath, animatedValueTag)); + } else { + std::vector> drivers(1); + drivers[0] = + std::make_unique(eventPath, animatedValueTag); + eventDrivers_.insert({key, std::move(drivers)}); + } +} + +void NativeAnimatedNodesManager::removeAnimatedEventFromView( + Tag viewTag, + const std::string& eventName, + Tag animatedValueTag) { + const auto key = EventAnimationDriverKey{ + viewTag, EventEmitter::normalizeEventType(eventName)}; + auto driversIter = eventDrivers_.find(key); + if (driversIter != eventDrivers_.end()) { + auto& drivers = driversIter->second; + std::erase_if(drivers, [animatedValueTag](auto& it) { + return it->getAnimatedNodeTag() == animatedValueTag; + }); + } +} + +static thread_local bool isOnRenderThread_{false}; + +void NativeAnimatedNodesManager::handleAnimatedEvent( + Tag viewTag, + const std::string& eventName, + const EventPayload& eventPayload) { + // We currently reject events that are not on the same thread as `onRender` + // callbacks, as the assumption is these events can synchronously update + // UI components or otherwise Animated nodes with single-threaded assumptions. + // While we could dispatch event handling back to the UI thread using the + // scheduleOnUI helper, we are not yet doing that because it would violate + // the assumption that the events have synchronous side-effects. We can + // revisit this decision later. + if (!isOnRenderThread_) { + return; + } + + if (!eventDrivers_.empty()) { + bool foundAtLeastOneDriver = false; + + const auto key = EventAnimationDriverKey{ + viewTag, EventEmitter::normalizeEventType(eventName)}; + if (auto driversIter = eventDrivers_.find(key); + driversIter != eventDrivers_.end()) { + auto& drivers = driversIter->second; + if (!drivers.empty()) { + foundAtLeastOneDriver = true; + } + for (const auto& driver : drivers) { + if (auto value = driver->getValueFromPayload(eventPayload)) { + auto node = + getAnimatedNode(driver->getAnimatedNodeTag()); + stopAnimationsForNode(node->tag()); + if (node->setRawValue(value.value())) { + updatedNodeTags_.insert(node->tag()); + } + } + } + } + + if (foundAtLeastOneDriver && !isGestureAnimationInProgress_) { + // There is an animation driver handling this event and + // gesture driven animation has not been started yet. + isGestureAnimationInProgress_ = true; + // Some platforms (e.g. iOS) have UI tick listener disable + // when there are no active animations. Calling + // `startRenderCallbackIfNeeded` will call platform specific code to + // register UI tick listener. + startRenderCallbackIfNeeded(); + } + } +} + +std::shared_ptr +NativeAnimatedNodesManager::ensureEventEmitterListener() { + if (!eventEmitterListener_) { + eventEmitterListener_ = std::make_shared( + [weakSelf = weak_from_this()]( + Tag tag, + const std::string& eventName, + const EventPayload& payload) -> bool { + if (auto self = weakSelf.lock()) { + self->handleAnimatedEvent(tag, eventName, payload); + } + return false; + }); + } + return eventEmitterListener_; +} + +void NativeAnimatedNodesManager::startRenderCallbackIfNeeded() { + if (startOnRenderCallback_) { + startOnRenderCallback_([weakSelf = weak_from_this()]() { + if (auto self = weakSelf.lock()) { + self->onRender(); + } + }); + + if (isOnRenderThread_) { + // Calling startOnRenderCallback_ will register a UI tick listener. + // The UI ticker listener will not be called until the next frame. + // That's why, in case this is called from the UI thread, we need to + // proactivelly trigger the animation loop to avoid showing stale frames. + onRender(); + } + } +} + +void NativeAnimatedNodesManager::stopRenderCallbackIfNeeded() { + if (stopOnRenderCallback_) { + stopOnRenderCallback_(); + } +} + +bool NativeAnimatedNodesManager::isAnimationUpdateNeeded() const { + return !activeAnimations_.empty() || !updatedNodeTags_.empty() || + isGestureAnimationInProgress_; +} + +void NativeAnimatedNodesManager::updateNodes( + const std::set& finishedAnimationValueNodes) { + auto nodesQueue = std::deque{}; + + const auto is_node_connected_to_finished_animation = + [&finishedAnimationValueNodes]( + const std::shared_ptr& node, + int nodeTag, + bool parentFinishedAnimation) -> bool { + return parentFinishedAnimation || + (node->type() == AnimatedNodeType::Value && + finishedAnimationValueNodes.contains(nodeTag)); + }; + +#ifdef REACT_NATIVE_DEBUG + int activeNodesCount = 0; + int updatedNodesCount = 0; +#endif + + // STEP 1. + // BFS over graph of nodes. Update `mIncomingNodes` attribute for each node + // during that BFS. Store number of visited nodes in `activeNodesCount`. We + // "execute" active animations as a part of this step. + + animatedGraphBFSColor_++; + if (animatedGraphBFSColor_ == AnimatedNode::INITIAL_BFS_COLOR) { + animatedGraphBFSColor_++; + } + + for (const auto& nodeTag : updatedNodeTags_) { + if (auto node = getAnimatedNode(nodeTag)) { + if (node->bfsColor != animatedGraphBFSColor_) { + node->bfsColor = animatedGraphBFSColor_; +#ifdef REACT_NATIVE_DEBUG + activeNodesCount++; +#endif + const auto connectedToFinishedAnimation = + is_node_connected_to_finished_animation(node, nodeTag, false); + nodesQueue.emplace_back( + NodesQueueItem{std::move(node), connectedToFinishedAnimation}); + } + } + } + + while (!nodesQueue.empty()) { + auto nextNode = std::move(nodesQueue.front()); + nodesQueue.pop_front(); + // in Animated, value nodes like RGBA are parents and Color node is child + // (the opposite of tree structure) + for (const auto childTag : nextNode.node->children()) { + auto child = getAnimatedNode(childTag); + child->activeIncomingNodes++; + if (child->bfsColor != animatedGraphBFSColor_) { + child->bfsColor = animatedGraphBFSColor_; +#ifdef REACT_NATIVE_DEBUG + activeNodesCount++; +#endif + const auto connectedToFinishedAnimation = + is_node_connected_to_finished_animation( + child, childTag, nextNode.connectedToFinishedAnimation); + nodesQueue.emplace_back( + NodesQueueItem{std::move(child), connectedToFinishedAnimation}); + } + } + } + + // STEP 2 + // BFS over the graph of active nodes in topological order -> visit node only + // when all its "predecessors" in the graph have already been visited. It is + // important to visit nodes in that order as they may often use values of + // their predecessors in order to calculate "next state" of their own. We + // start by determining the starting set of nodes by looking for nodes with + // `activeIncomingNodes = 0` (those can only be the ones that we start BFS in + // the previous step). We store number of visited nodes in this step in + // `updatedNodesCount` + + animatedGraphBFSColor_++; + if (animatedGraphBFSColor_ == AnimatedNode::INITIAL_BFS_COLOR) { + animatedGraphBFSColor_++; + } + + for (const auto& nodeTag : updatedNodeTags_) { + if (auto node = getAnimatedNode(nodeTag)) { + if (node->activeIncomingNodes == 0 && + node->bfsColor != animatedGraphBFSColor_) { + node->bfsColor = animatedGraphBFSColor_; +#ifdef REACT_NATIVE_DEBUG + updatedNodesCount++; +#endif + const auto connectedToFinishedAnimation = + is_node_connected_to_finished_animation(node, nodeTag, false); + nodesQueue.emplace_back( + NodesQueueItem{std::move(node), connectedToFinishedAnimation}); + } + } + } + +// Run main "update" loop +#ifdef REACT_NATIVE_DEBUG + int cyclesDetected = 0; +#endif + while (!nodesQueue.empty()) { + auto nextNode = std::move(nodesQueue.front()); + nodesQueue.pop_front(); + if (nextNode.connectedToFinishedAnimation && + nextNode.node->type() == AnimatedNodeType::Props) { + if (auto propsNode = + std::static_pointer_cast(nextNode.node)) { + propsNode->update(/*forceFabricCommit*/ true); + }; + } else { + nextNode.node->update(); + } + + for (auto childTag : nextNode.node->children()) { + auto child = getAnimatedNode(childTag); + child->activeIncomingNodes--; + if (child->activeIncomingNodes == 0 && child->activeIncomingNodes == 0) { + child->bfsColor = animatedGraphBFSColor_; +#ifdef REACT_NATIVE_DEBUG + updatedNodesCount++; +#endif + const auto connectedToFinishedAnimation = + is_node_connected_to_finished_animation( + child, childTag, nextNode.connectedToFinishedAnimation); + nodesQueue.emplace_back( + NodesQueueItem{std::move(child), connectedToFinishedAnimation}); + } +#ifdef REACT_NATIVE_DEBUG + else if (child->bfsColor == animatedGraphBFSColor_) { + cyclesDetected++; + } +#endif + } + } + +#ifdef REACT_NATIVE_DEBUG + // Verify that we've visited *all* active nodes. Throw otherwise as this could + // mean there is a cycle in animated node graph, or that the graph is only + // partially set up. We also take advantage of the fact that all active nodes + // are visited in the step above so that all the nodes properties + // `activeIncomingNodes` are set to zero. In Fabric there can be race + // conditions between the JS thread setting up or tearing down animated nodes, + // and Fabric executing them on the UI thread, leading to temporary + // inconsistent states. + if (activeNodesCount != updatedNodesCount) { + if (warnedAboutGraphTraversal_) { + return; + } + warnedAboutGraphTraversal_ = true; + auto reason = cyclesDetected > 0 + ? ("cycles (" + std::to_string(cyclesDetected) + ")") + : "disconnected regions"; + LOG(ERROR) << "Detected animation cycle or disconnected graph. " + << "Looks like animated nodes graph has " << reason + << ", there are " << activeNodesCount + << " but toposort visited only " << updatedNodesCount; + } else { + warnedAboutGraphTraversal_ = false; + } +#endif + + updatedNodeTags_.clear(); +} + +bool NativeAnimatedNodesManager::onAnimationFrame(uint64_t timestamp) { + // Run all active animations + auto hasFinishedAnimations = false; + std::set finishedAnimationValueNodes; + for (const auto& [_id, driver] : activeAnimations_) { + driver->runAnimationStep(timestamp); + + if (driver->isComplete()) { + hasFinishedAnimations = true; + finishedAnimationValueNodes.insert(driver->animatedValueTag()); + } + } + + // Update all animated nodes + updateNodes(finishedAnimationValueNodes); + + // remove finished animations + if (hasFinishedAnimations) { + std::vector finishedAnimations; + for (const auto& [animationId, driver] : activeAnimations_) { + if (driver->isComplete()) { + if (getAnimatedNode(driver->animatedValueTag())) { + driver->stopAnimation(); + } + finishedAnimations.emplace_back(animationId); + } + } + for (const auto& id : finishedAnimations) { + activeAnimations_.erase(id); + } + } + + return commitProps(); +} + +std::optional NativeAnimatedNodesManager::managedProps( + Tag tag) { + std::lock_guard lock(connectedAnimatedNodesMutex_); + const auto iter = connectedAnimatedNodes_.find(tag); + if (iter != connectedAnimatedNodes_.end()) { + if (const auto node = getAnimatedNode(iter->second)) { + return node->props(); + } + } + + return {}; +} + +bool NativeAnimatedNodesManager::isOnRenderThread() const { + return isOnRenderThread_; +} + +// listeners +void NativeAnimatedNodesManager::startListeningToAnimatedNodeValue( + Tag tag, + ValueListenerCallback&& callback) { + if (auto iter = animatedNodes_.find(tag); iter != animatedNodes_.end() && + iter->second->type() == AnimatedNodeType::Value) { + static_pointer_cast(iter->second) + ->setValueListener(std::move(callback)); + } else { + LOG(ERROR) << "startListeningToAnimatedNodeValue: Animated node [" << tag + << "] does not exist, or is not a 'value' node"; + } +} + +void NativeAnimatedNodesManager::stopListeningToAnimatedNodeValue(Tag tag) { + if (auto iter = animatedNodes_.find(tag); iter != animatedNodes_.end() && + iter->second->type() == AnimatedNodeType::Value) { + static_pointer_cast(iter->second) + ->setValueListener(nullptr); + } else { + LOG(ERROR) << "stopListeningToAnimatedNodeValue: Animated node [" << tag + << "] does not exist, or is not a 'value' node"; + } +} + +void NativeAnimatedNodesManager::schedulePropsCommit( + Tag viewTag, + const folly::dynamic& props, + bool layoutStyleUpdated, + bool forceFabricCommit) { + // When fabricCommitCallback_ & directManipulationCallback_ are both + // available, we commit layout props via Fabric and the other using direct + // manipulation; if only one is available, we commit all props using that + if (fabricCommitCallback_ != nullptr && + (layoutStyleUpdated || forceFabricCommit || + directManipulationCallback_ == nullptr)) { + mergeObjects(updateViewProps_[viewTag], props); + } else if (directManipulationCallback_ != nullptr) { + mergeObjects(updateViewPropsDirect_[viewTag], props); + } +} + +void NativeAnimatedNodesManager::onRender() { + TRACE_EVENT("rncxx", "NativeAnimatedNodesManager::onRender"); + TRACE_COUNTER("rncxx", "numActiveAnimations", activeAnimations_.size()); + + isOnRenderThread_ = true; + + // Run operations scheduled from AnimatedModule + std::vector operations; + { + std::lock_guard lock(uiTasksMutex_); + std::swap(operations_, operations); + } + + for (auto& task : operations) { + task(); + } + + // Step through the animation loop + if (isAnimationUpdateNeeded()) { + auto ms = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); + + auto containsChange = + onAnimationFrame(static_cast(ms * TicksPerMs)); + + if (!containsChange) { + // The last animation tick didn't result in any changes to the UI. + // It is safe to assume any gesture animation that was in progress has + // completed. + isGestureAnimationInProgress_ = false; + } + } else { + // There is no active animation. Stop the render callback. + stopRenderCallbackIfNeeded(); + } +} + +bool NativeAnimatedNodesManager::commitProps() { + bool containsChange = + !updateViewProps_.empty() || !updateViewPropsDirect_.empty(); + + if (fabricCommitCallback_ != nullptr) { + if (!updateViewProps_.empty()) { + fabricCommitCallback_(updateViewProps_); + updateViewProps_.clear(); + } + } else { + LOG(ERROR) + << "Failed to commit native animation, since Fabric commit callback is not set"; + } + + if (directManipulationCallback_ != nullptr) { + for (const auto& [viewTag, props] : updateViewPropsDirect_) { + directManipulationCallback_(viewTag, folly::dynamic(props)); + } + updateViewPropsDirect_.clear(); + } else { + LOG(ERROR) + << "Failed to commit native animation, since direct manipulation callback is not set"; + } + + return containsChange; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManager.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManager.h new file mode 100644 index 00000000000..588e24d8ab8 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManager.h @@ -0,0 +1,232 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +class AnimatedNode; +class AnimationDriver; +class Scheduler; + +using ValueListenerCallback = std::function; +using UiTask = std::function; + +using EndResult = NativeAnimatedTurboModuleEndResult< + bool, + std::optional, + std::optional>; + +using AnimationEndCallback = AsyncCallback; + +template <> +struct Bridging + : NativeAnimatedTurboModuleEndResultBridging {}; + +class NativeAnimatedNodesManager + : public std::enable_shared_from_this { + public: + using DirectManipulationCallback = + std::function; + using FabricCommitCallback = + std::function&)>; + using StartOnRenderCallback = std::function&&)>; + using StopOnRenderCallback = std::function; + + explicit NativeAnimatedNodesManager( + DirectManipulationCallback&& directManipulationCallback, + FabricCommitCallback&& fabricCommitCallback = nullptr, + StartOnRenderCallback&& startOnRenderCallback = nullptr, + StopOnRenderCallback&& stopOnRenderCallback = nullptr) noexcept; + + ~NativeAnimatedNodesManager() = default; + + template < + typename T, + typename = std::enable_if_t>> + std::shared_ptr getAnimatedNode(Tag tag) const + requires(std::is_base_of_v) + { + if (auto it = animatedNodes_.find(tag); it != animatedNodes_.end()) { + return std::static_pointer_cast(it->second); + } + return nullptr; + } + + std::optional getValue(Tag tag); + + // graph + + void createAnimatedNode(Tag tag, const folly::dynamic& config); + + void connectAnimatedNodes(Tag parentTag, Tag childTag); + + void connectAnimatedNodeToView(Tag propsNodeTag, Tag viewTag); + + void disconnectAnimatedNodes(Tag parentTag, Tag childTag); + + void disconnectAnimatedNodeFromView(Tag propsNodeTag, Tag viewTag); + + void restoreDefaultValues(Tag tag); + + void dropAnimatedNode(Tag tag); + + // mutations + + void setAnimatedNodeValue(Tag tag, double value); + + void setAnimatedNodeOffset(Tag tag, double offset); + + void flattenAnimatedNodeOffset(Tag tag); + + void extractAnimatedNodeOffset(Tag tag); + + void updateAnimatedNodeConfig(Tag tag, const folly::dynamic& config); + + // drivers + + void startAnimatingNode( + int animationId, + Tag animatedNodeTag, + const folly::dynamic& config, + const std::optional& endCallback); + + void stopAnimation(int animationId, bool isTrackingAnimation = false); + + void addAnimatedEventToView( + Tag viewTag, + const std::string& eventName, + const folly::dynamic& eventMapping); + + void removeAnimatedEventFromView( + Tag viewTag, + const std::string& eventName, + Tag animatedValueTag); + + std::shared_ptr getEventEmitterListener() { + return ensureEventEmitterListener(); + } + // listeners + + void startListeningToAnimatedNodeValue( + Tag tag, + ValueListenerCallback&& callback); + + void stopListeningToAnimatedNodeValue(Tag tag); + + void schedulePropsCommit( + Tag viewTag, + const folly::dynamic& props, + bool layoutStyleUpdated, + bool forceFabricCommit); + + /** + * Commits all pending animated property updates to their respective views. + * + * This method is the final step in the animation pipeline that applies + * calculated property values to the actual UI components. It uses + * Fabric-based updates if layout properties are affected, otherwise uses + * direct manipulation. + * + * returns boolean indicating whether any changes were committed to views. + * Returns true if no changes were made, which helps the animation + * system determine if animations are still active. + */ + bool commitProps(); + + void scheduleOnUI(UiTask&& task) { + std::lock_guard lock(uiTasksMutex_); + operations_.push_back(std::move(task)); + + // Whenever a batch is flushed to the UI thread, start the onRender + // callbacks to guarantee they run at least once. E.g., to execute + // setValue calls. + startRenderCallbackIfNeeded(); + } + + void onRender(); + + void startRenderCallbackIfNeeded(); + + void updateNodes(const std::set& finishedAnimationValueNodes = {}); + + std::optional managedProps(Tag tag); + + bool isOnRenderThread() const; + + private: + void stopRenderCallbackIfNeeded(); + + bool onAnimationFrame(uint64_t timestamp); + + bool isAnimationUpdateNeeded() const; + + void stopAnimationsForNode(Tag nodeTag); + + std::shared_ptr ensureEventEmitterListener(); + + void handleAnimatedEvent( + Tag tag, + const std::string& eventName, + const EventPayload& payload); + + std::unique_ptr animatedNode( + Tag tag, + const folly::dynamic& config); + + std::unordered_map> animatedNodes_; + std::unordered_map connectedAnimatedNodes_; + std::unordered_map> activeAnimations_; + std::unordered_map< + EventAnimationDriverKey, + std::vector>, + std::hash> + eventDrivers_; + std::unordered_set updatedNodeTags_; + + std::mutex connectedAnimatedNodesMutex_; + + std::mutex uiTasksMutex_; + std::vector operations_; + + bool isGestureAnimationInProgress_{false}; + + // React context required to commit props onto Component View + DirectManipulationCallback directManipulationCallback_; + FabricCommitCallback fabricCommitCallback_; + StartOnRenderCallback startOnRenderCallback_; + StopOnRenderCallback stopOnRenderCallback_; + + std::shared_ptr eventEmitterListener_{nullptr}; + + std::unordered_map updateViewProps_{}; + std::unordered_map updateViewPropsDirect_{}; + + int animatedGraphBFSColor_ = 0; +#ifdef REACT_NATIVE_DEBUG + bool warnedAboutGraphTraversal_ = false; +#endif + + friend class ColorAnimatedNode; + friend class AnimationDriver; + friend class AnimationTestsBase; +}; +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManagerProvider.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManagerProvider.cpp new file mode 100644 index 00000000000..b3c968c9766 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManagerProvider.cpp @@ -0,0 +1,163 @@ +/* + * 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. + */ + +#include "NativeAnimatedNodesManagerProvider.h" + +#include +#include +#include + +namespace facebook::react { + +UIManagerNativeAnimatedDelegateImpl::UIManagerNativeAnimatedDelegateImpl( + std::weak_ptr nativeAnimatedNodesManager) + : nativeAnimatedNodesManager_(std::move(nativeAnimatedNodesManager)) {} + +void UIManagerNativeAnimatedDelegateImpl::runAnimationFrame() { + if (auto nativeAnimatedNodesManagerStrong = + nativeAnimatedNodesManager_.lock()) { + nativeAnimatedNodesManagerStrong->onRender(); + } +} + +NativeAnimatedNodesManagerProvider::NativeAnimatedNodesManagerProvider( + NativeAnimatedNodesManager::StartOnRenderCallback startOnRenderCallback, + NativeAnimatedNodesManager::StopOnRenderCallback stopOnRenderCallback) + : eventEmitterListenerContainer_( + std::make_shared()), + startOnRenderCallback_(std::move(startOnRenderCallback)), + stopOnRenderCallback_(std::move(stopOnRenderCallback)) {} + +std::shared_ptr +NativeAnimatedNodesManagerProvider::getOrCreate(jsi::Runtime& runtime) { + if (!uiManagerBinding_.lock()) { + uiManagerBinding_ = UIManagerBinding::getBinding(runtime); + } + + if (nativeAnimatedNodesManager_ == nullptr) { + auto fabricCommitCallback = + [uiManagerBindingWeak = uiManagerBinding_]( + std::unordered_map& tagToProps) { + if (auto uiManagerBinding = uiManagerBindingWeak.lock()) { + uiManagerBinding->getUIManager().updateShadowTree(tagToProps); + } else { + LOG(WARNING) + << "UIManager is not initialized for Fabric commit callback"; + } + }; + + auto directManipulationCallback = + [uiManagerBindingWeak = uiManagerBinding_]( + Tag viewTag, const folly::dynamic& props) { + if (auto uiManagerBinding = uiManagerBindingWeak.lock()) { + uiManagerBinding->getUIManager().synchronouslyUpdateViewOnUIThread( + viewTag, props); + } + }; + + nativeAnimatedNodesManager_ = std::make_shared( + std::move(directManipulationCallback), + std::move(fabricCommitCallback), + std::move(startOnRenderCallback_), + std::move(stopOnRenderCallback_)); + + addEventEmitterListener( + nativeAnimatedNodesManager_->getEventEmitterListener()); + + if (auto uiManagerBinding = uiManagerBinding_.lock()) { + uiManagerBinding->getUIManager().addEventListener( + std::make_shared( + [eventEmitterListenerContainerWeak = + std::weak_ptr( + eventEmitterListenerContainer_)]( + const RawEvent& rawEvent) { + const auto& eventTarget = rawEvent.eventTarget; + const auto& eventPayload = rawEvent.eventPayload; + if (eventTarget && eventPayload) { + if (auto eventEmitterListenerContainer = + eventEmitterListenerContainerWeak.lock(); + eventEmitterListenerContainer != nullptr) { + return eventEmitterListenerContainer->willDispatchEvent( + eventTarget->getTag(), rawEvent.type, *eventPayload); + } + } + return false; + })); + + nativeAnimatedDelegate_ = + std::make_shared( + nativeAnimatedNodesManager_); + + uiManagerBinding->getUIManager().setNativeAnimatedDelegate( + nativeAnimatedDelegate_); + + animatedMountingOverrideDelegate_ = + std::make_shared( + [nativeAnimatedNodesManager = + std::weak_ptr( + nativeAnimatedNodesManager_)]( + Tag tag) -> std::optional { + if (auto nativeAnimatedNodesManagerStrong = + nativeAnimatedNodesManager.lock()) { + return nativeAnimatedNodesManagerStrong->managedProps(tag); + } + return std::nullopt; + }, + uiManagerBinding_); + + // Register on existing surfaces + uiManagerBinding->getUIManager().getShadowTreeRegistry().enumerate( + [animatedMountingOverrideDelegate = + std::weak_ptr( + animatedMountingOverrideDelegate_)]( + const ShadowTree& shadowTree, bool& /*stop*/) { + shadowTree.getMountingCoordinator()->setMountingOverrideDelegate( + animatedMountingOverrideDelegate); + }); + // Register on surfaces started in the future + uiManagerBinding->getUIManager().setOnSurfaceStartCallback( + [animatedMountingOverrideDelegate = + std::weak_ptr( + animatedMountingOverrideDelegate_)]( + const ShadowTree& shadowTree) { + shadowTree.getMountingCoordinator()->setMountingOverrideDelegate( + animatedMountingOverrideDelegate); + }); + } + } + + return nativeAnimatedNodesManager_; +} + +void NativeAnimatedNodesManagerProvider::addEventEmitterListener( + const std::shared_ptr& listener) { + eventEmitterListenerContainer_->addListener(listener); +} + +std::shared_ptr +NativeAnimatedNodesManagerProvider::getEventEmitterListener() { + if (!eventEmitterListener_) { + eventEmitterListener_ = std::make_shared( + [eventEmitterListenerContainerWeak = + std::weak_ptr( + eventEmitterListenerContainer_)]( + Tag tag, + const std::string& eventName, + const EventPayload& payload) -> bool { + if (auto eventEmitterListenerContainer = + eventEmitterListenerContainerWeak.lock(); + eventEmitterListenerContainer != nullptr) { + return eventEmitterListenerContainer->willDispatchEvent( + tag, eventName, payload); + } + return false; + }); + } + return eventEmitterListener_; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManagerProvider.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManagerProvider.h new file mode 100644 index 00000000000..17d82a85c47 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/NativeAnimatedNodesManagerProvider.h @@ -0,0 +1,68 @@ +/* + * 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. + */ + +#pragma once + +#include +#include "NativeAnimatedNodesManager.h" + +namespace facebook::react { + +class UIManagerBinding; + +class UIManagerNativeAnimatedDelegateImpl + : public UIManagerNativeAnimatedDelegate { + public: + explicit UIManagerNativeAnimatedDelegateImpl( + std::weak_ptr nativeAnimatedNodesManager); + + void runAnimationFrame() override; + + private: + std::weak_ptr nativeAnimatedNodesManager_; +}; +class AnimatedMountingOverrideDelegate; + +class NativeAnimatedNodesManagerProvider { + public: + NativeAnimatedNodesManagerProvider( + NativeAnimatedNodesManager::StartOnRenderCallback startOnRenderCallback = + nullptr, + NativeAnimatedNodesManager::StopOnRenderCallback stopOnRenderCallback = + nullptr); + + virtual ~NativeAnimatedNodesManagerProvider() = default; + + virtual std::shared_ptr getOrCreate( + jsi::Runtime& runtime); + + std::shared_ptr get() { + return nativeAnimatedNodesManager_; + } + + // Native Event Listeners + void addEventEmitterListener( + const std::shared_ptr& listener); + + std::shared_ptr getEventEmitterListener(); + + protected: + std::shared_ptr nativeAnimatedNodesManager_; + std::weak_ptr uiManagerBinding_; + + std::shared_ptr eventEmitterListenerContainer_; + std::shared_ptr eventEmitterListener_; + + std::shared_ptr nativeAnimatedDelegate_; + std::shared_ptr + animatedMountingOverrideDelegate_; + + NativeAnimatedNodesManager::StartOnRenderCallback startOnRenderCallback_; + NativeAnimatedNodesManager::StopOnRenderCallback stopOnRenderCallback_; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/AnimationDriver.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/AnimationDriver.cpp new file mode 100644 index 00000000000..0486079b418 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/AnimationDriver.cpp @@ -0,0 +1,105 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "AnimationDriver.h" + +#include +#include +#include +#include + +namespace facebook::react { + +std::optional AnimationDriver::getDriverTypeByName( + const std::string& driverTypeName) { + static std::unordered_map typeNames = { + {"frames", AnimationDriverType::Frames}, + {"spring", AnimationDriverType::Spring}, + {"decay", AnimationDriverType::Decay}}; + if (auto iter = typeNames.find(driverTypeName); iter != typeNames.end()) { + return iter->second; + } + return std::nullopt; +} + +AnimationDriver::AnimationDriver( + int id, + Tag animatedValueTag, + std::optional endCallback, + folly::dynamic config, + NativeAnimatedNodesManager* manager) + : endCallback_(std::move(endCallback)), + id_(id), + animatedValueTag_(animatedValueTag), + manager_(manager), + config_(std::move(config)) { + onConfigChanged(); +} + +void AnimationDriver::startAnimation() { + startFrameTimeMs_ = -1; + isStarted_ = true; +} + +void AnimationDriver::stopAnimation(bool /*ignoreCompletedHandlers*/) { + std::optional value = std::nullopt; + if (auto node = + manager_->getAnimatedNode(animatedValueTag_)) { + value = node->value(); + } else { + LOG(ERROR) + << "animatedValueTag should be associated with a ValueAnimatedNode"; + } + if (endCallback_) { + endCallback_.value().call({.finished = true, .value = value}); + } +} + +void AnimationDriver::runAnimationStep(double renderingTime) { + if (!isStarted_ || isComplete_) { + return; + } + + // ticks are 100 nanoseconds, divide by 10000 to get milliseconds. + const auto frameTimeMs = renderingTime / TicksPerMs; + auto restarting = false; + if (startFrameTimeMs_ < 0) { + startFrameTimeMs_ = frameTimeMs; + restarting = true; + } + + const auto timeDeltaMs = frameTimeMs - startFrameTimeMs_; + const auto isComplete = update(timeDeltaMs, restarting); + + if (isComplete) { + if (iterations_ == -1 || ++currentIteration_ < iterations_) { + startFrameTimeMs_ = -1; + } else { + isComplete_ = true; + } + } +} + +void AnimationDriver::updateConfig(folly::dynamic config) { + config_ = std::move(config); + onConfigChanged(); +} + +void AnimationDriver::onConfigChanged() { + iterations_ = (config_.count("iterations") != 0u) + ? static_cast(config_["iterations"].asDouble()) + : 1; + isComplete_ = iterations_ == 0; + currentIteration_ = 1; + startFrameTimeMs_ = -1; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/AnimationDriver.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/AnimationDriver.h new file mode 100644 index 00000000000..529561a1815 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/AnimationDriver.h @@ -0,0 +1,100 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include +#include + +namespace facebook::react { + +enum class AnimationDriverType { + Frames, + Spring, + Decay, +}; + +class ValueAnimatedNode; +class AnimationDriver : public std::enable_shared_from_this { + public: + AnimationDriver( + int id, + Tag animatedValueTag, + std::optional endCallback, + folly::dynamic config, + NativeAnimatedNodesManager* manager); + virtual ~AnimationDriver() = default; + void startAnimation(); + void stopAnimation(bool ignoreCompletedHandlers = false); + + inline constexpr int Id() { + return id_; + } + + inline constexpr Tag animatedValueTag() { + return animatedValueTag_; + } + + inline std::optional endCallback() noexcept { + return endCallback_; + } + + virtual double toValue() { + return 0; + } + + bool isComplete() { + return isComplete_; + } + + virtual void runAnimationStep(double renderingTime); + + virtual void updateConfig(folly::dynamic config); + +#ifdef REACT_NATIVE_DEBUG + std::string debugID() const { + return (config_.count("debugID") != 0u) ? config_["debugID"].asString() + : ""; + } +#endif + + static std::optional getDriverTypeByName( + const std::string& driverTypeName); + + protected: + virtual bool update(double /*timeDeltaMs*/, bool /*restarting*/) { + return true; + } + + void markNodeUpdated(Tag tag) { + manager_->updatedNodeTags_.insert(tag); + } + + std::optional endCallback_; + int id_{0}; + Tag animatedValueTag_{}; // Tag of a ValueAnimatedNode + int iterations_{0}; + NativeAnimatedNodesManager* manager_; + + bool isComplete_{false}; + int currentIteration_{0}; + double startFrameTimeMs_{-1}; + + bool isStarted_{false}; + bool ignoreCompletedHandlers_{false}; + + folly::dynamic config_{}; + + private: + void onConfigChanged(); +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/AnimationDriverUtils.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/AnimationDriverUtils.h new file mode 100644 index 00000000000..a1077e691c1 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/AnimationDriverUtils.h @@ -0,0 +1,64 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include + +static constexpr std::string_view ExtrapolateTypeIdentity = "identity"; +static constexpr std::string_view ExtrapolateTypeClamp = "clamp"; +static constexpr std::string_view ExtrapolateTypeExtend = "extend"; + +static constexpr double SingleFrameIntervalMs = 1000.0 / 60.0; + +static constexpr double TicksPerMs = 10000.0; // ticks are 100 nanoseconds + +namespace { + +inline double interpolate( + double inputValue, + double inputMin, + double inputMax, + double outputMin, + double outputMax, + const std::string_view& extrapolateLeft, + const std::string_view& extrapolateRight) { + auto result = inputValue; + + // Extrapolate + if (result < inputMin) { + if (extrapolateLeft == ExtrapolateTypeIdentity) { + return result; + } else if (extrapolateLeft == ExtrapolateTypeClamp) { + result = inputMin; + } + } + + if (result > inputMax) { + if (extrapolateRight == ExtrapolateTypeIdentity) { + return result; + } else if (extrapolateRight == ExtrapolateTypeClamp) { + result = inputMax; + } + } + + if (inputMin == inputMax) { + if (inputValue <= inputMin) { + return outputMin; + } + return outputMax; + } + + return outputMin + + (outputMax - outputMin) * (result - inputMin) / (inputMax - inputMin); +} + +} // namespace diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/DecayAnimationDriver.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/DecayAnimationDriver.cpp new file mode 100644 index 00000000000..cd7eff60b2c --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/DecayAnimationDriver.cpp @@ -0,0 +1,81 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "DecayAnimationDriver.h" +#include +#include + +namespace facebook::react { +DecayAnimationDriver::DecayAnimationDriver( + int id, + Tag animatedValueTag, + std::optional endCallback, + const folly::dynamic& config, + NativeAnimatedNodesManager* manager) + : AnimationDriver( + id, + animatedValueTag, + std::move(endCallback), + config, + manager), + velocity_(config["velocity"].asDouble()), + deceleration_(config_["deceleration"].asDouble()) { + react_native_assert(deceleration_ > 0); +} + +std::tuple DecayAnimationDriver::getValueAndVelocityForTime( + double time) const { + const auto value = fromValue_.value() + + velocity_ / (1 - deceleration_) * + (1 - std::exp(-(1 - deceleration_) * (1000 * time))); + return std::make_tuple( + static_cast(value), + 42.0f); // we don't need the velocity, so set it to a dummy value +} + +bool DecayAnimationDriver::update(double timeDeltaMs, bool restarting) { + if (const auto node = + manager_->getAnimatedNode(animatedValueTag_)) { + if (restarting) { + const auto value = node->rawValue(); + if (!fromValue_.has_value()) { + // First iteration, assign fromValue based on AnimatedValue + fromValue_ = value; + } else { + // Not the first iteration, reset AnimatedValue based on + // originalValue + if (node->setRawValue(fromValue_.value())) { + markNodeUpdated(node->tag()); + } + } + + lastValue_ = value; + } + + const auto [value, velocity] = + getValueAndVelocityForTime(timeDeltaMs / 1000.0); + auto isComplete = + lastValue_.has_value() && std::abs(value - lastValue_.value()) < 0.1; + if (!restarting && isComplete) { + return true; + } else { + lastValue_ = value; + if (node->setRawValue(value)) { + markNodeUpdated(node->tag()); + } + return false; + } + } + + return true; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/DecayAnimationDriver.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/DecayAnimationDriver.h new file mode 100644 index 00000000000..913ca4c309e --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/DecayAnimationDriver.h @@ -0,0 +1,40 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "AnimationDriver.h" + +namespace facebook::react { + +class DecayAnimationDriver : public AnimationDriver { + public: + DecayAnimationDriver( + int id, + Tag animatedValueTag, + std::optional endCallback, + const folly::dynamic& config, + NativeAnimatedNodesManager* manager); + + protected: + bool update(double timeDeltaMs, bool restarting) override; + + private: + std::tuple getValueAndVelocityForTime(double time) const; + + private: + double velocity_{0}; + double deceleration_{0}; + std::optional fromValue_{std::nullopt}; + std::optional lastValue_{0}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/FrameAnimationDriver.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/FrameAnimationDriver.cpp new file mode 100644 index 00000000000..9423272eae9 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/FrameAnimationDriver.cpp @@ -0,0 +1,117 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "FrameAnimationDriver.h" + +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +FrameAnimationDriver::FrameAnimationDriver( + int id, + Tag animatedValueTag, + std::optional endCallback, + const folly::dynamic& config, + NativeAnimatedNodesManager* manager) + : AnimationDriver( + id, + animatedValueTag, + std::move(endCallback), + config, + manager) { + onConfigChanged(); +} + +double FrameAnimationDriver::toValue() { + return toValue_; +} + +void FrameAnimationDriver::updateConfig(folly::dynamic config) { + AnimationDriver::updateConfig(config); + onConfigChanged(); +} + +void FrameAnimationDriver::onConfigChanged() { + auto frames = config_["frames"]; + react_native_assert(frames.type() == folly::dynamic::ARRAY); + for (const auto& frame : frames) { + auto frameValue = frame.asDouble(); + frames_.push_back(frameValue); + } + toValue_ = config_["toValue"].asDouble(); +} + +bool FrameAnimationDriver::update(double timeDeltaMs, bool /*restarting*/) { + if (auto node = + manager_->getAnimatedNode(animatedValueTag_)) { + if (!startValue_) { + startValue_ = node->rawValue(); + } + + const auto startIndex = + static_cast(timeDeltaMs / SingleFrameIntervalMs); + assert(startIndex >= 0); + const auto nextIndex = startIndex + 1; + + double nextValue = NAN; + auto isComplete = false; + if (nextIndex >= frames_.size()) { + if (iterations_ == -1 || currentIteration_ < iterations_) { + // Use last frame value, just in case it's different from toValue_ + nextValue = startValue_.value() + + frames_[frames_.size() - 1] * (toValue_ - startValue_.value()); + } else { + nextValue = toValue_; + } + isComplete = true; + } else { + const auto fromInterval = startIndex * SingleFrameIntervalMs; + const auto toInterval = nextIndex * SingleFrameIntervalMs; + const auto fromValue = frames_[startIndex]; + const auto toValue = frames_[nextIndex]; + + // Map timestamp to frame value (frames_ elements are in [0,1]) + const auto frameOutput = interpolate( + timeDeltaMs, + fromInterval, + toInterval, + fromValue, + toValue, + ExtrapolateTypeExtend, + ExtrapolateTypeExtend); + + // Map frame to output value + nextValue = interpolate( + frameOutput, + 0, + 1, + startValue_.value(), + toValue_, + ExtrapolateTypeExtend, + ExtrapolateTypeExtend); + } + + if (node->setRawValue(nextValue)) { + markNodeUpdated(node->tag()); + } + + return isComplete; + } + + return true; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/FrameAnimationDriver.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/FrameAnimationDriver.h new file mode 100644 index 00000000000..97664672799 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/FrameAnimationDriver.h @@ -0,0 +1,42 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "AnimationDriver.h" + +namespace facebook::react { + +class FrameAnimationDriver : public AnimationDriver { + public: + FrameAnimationDriver( + int id, + Tag animatedValueTag, + std::optional endCallback, + const folly::dynamic& config, + NativeAnimatedNodesManager* manager); + + double toValue() override; + + protected: + bool update(double timeDeltaMs, bool restarting) override; + + void updateConfig(folly::dynamic config) override; + + private: + void onConfigChanged(); + + std::vector frames_{}; + double toValue_{0}; + std::optional startValue_{}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/SpringAnimationDriver.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/SpringAnimationDriver.cpp new file mode 100644 index 00000000000..02a80b3b870 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/SpringAnimationDriver.cpp @@ -0,0 +1,148 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "SpringAnimationDriver.h" +#include +#include + +namespace facebook::react { + +static constexpr auto MaxDeltaTimeMs = 4.0 * 1000.0 / 60.0; + +SpringAnimationDriver::SpringAnimationDriver( + int id, + Tag animatedValueTag, + std::optional endCallback, + const folly::dynamic& config, + NativeAnimatedNodesManager* manager) + : AnimationDriver( + id, + animatedValueTag, + std::move(endCallback), + config, + manager), + springStiffness_(config_["stiffness"].asDouble()), + springDamping_(config_["damping"].asDouble()), + springMass_(config_["mass"].asDouble()), + initialVelocity_(config_["initialVelocity"].asDouble()), + endValue_(config_["toValue"].asDouble()), + restSpeedThreshold_(config_["restSpeedThreshold"].asDouble()), + displacementFromRestThreshold_( + config_["restDisplacementThreshold"].asDouble()), + overshootClampingEnabled_(config_["overshootClamping"].asBool()) {} + +std::tuple SpringAnimationDriver::getValueAndVelocityForTime( + double time) const { + const auto startValue = fromValue_.value(); + const auto toValue = endValue_; + const auto c = springDamping_; + const auto m = springMass_; + const auto k = springStiffness_; + const auto v0 = -initialVelocity_; + + const auto zeta = c / (2 * std::sqrt(k * m)); + const auto omega0 = std::sqrt(k / m); + const auto omega1 = omega0 * std::sqrt(1.0 - (zeta * zeta)); + const auto x0 = toValue - startValue; + + if (zeta < 1) { + const auto envelope = std::exp(-zeta * omega0 * time); + const auto value = static_cast( + toValue - + envelope * + ((v0 + zeta * omega0 * x0) / omega1 * std::sin(omega1 * time) + + x0 * std::cos(omega1 * time))); + const auto velocity = zeta * omega0 * envelope * + (std::sin(omega1 * time) * (v0 + zeta * omega0 * x0) / omega1 + + x0 * std::cos(omega1 * time)) - + envelope * + (std::cos(omega1 * time) * (v0 + zeta * omega0 * x0) - + omega1 * x0 * std::sin(omega1 * time)); + return std::make_tuple(value, velocity); + } else { + const auto envelope = std::exp(-omega0 * time); + const auto value = static_cast( + endValue_ - envelope * (x0 + (v0 + omega0 * x0) * time)); + const auto velocity = + envelope * (v0 * (time * omega0 - 1) + time * x0 * (omega0 * omega0)); + return std::make_tuple(value, velocity); + } +} + +bool SpringAnimationDriver::update(double timeDeltaMs, bool restarting) { + if (const auto node = + manager_->getAnimatedNode(animatedValueTag_)) { + if (restarting) { + if (!fromValue_.has_value()) { + fromValue_ = node->rawValue(); + } else { + if (node->setRawValue(fromValue_.value())) { + markNodeUpdated(node->tag()); + } + } + + // Spring animations run a frame behind JS driven animations if we do + // not start the first frame at 16ms. + lastTime_ = timeDeltaMs - SingleFrameIntervalMs; + timeAccumulator_ = 0.0; + } + + // clamp the amount of timeDeltaMs to avoid stuttering in the UI. + // We should be able to catch up in a subsequent advance if necessary. + auto adjustedDeltaTime = timeDeltaMs - lastTime_; + if (adjustedDeltaTime > MaxDeltaTimeMs) { + adjustedDeltaTime = MaxDeltaTimeMs; + } + timeAccumulator_ += adjustedDeltaTime; + lastTime_ = timeDeltaMs; + + auto [value, velocity] = + getValueAndVelocityForTime(timeAccumulator_ / 1000.0); + + auto isComplete = false; + if (isAtRest(velocity, value, endValue_) || + (overshootClampingEnabled_ && isOvershooting(value))) { + if (springStiffness_ > 0) { + value = static_cast(endValue_); + } else { + endValue_ = value; + } + + isComplete = true; + } + + if (node->setRawValue(value)) { + markNodeUpdated(node->tag()); + } + + return isComplete; + } + + return true; +} + +bool SpringAnimationDriver::isAtRest( + double currentVelocity, + double currentValue, + double endValue) const { + return std::abs(currentVelocity) <= restSpeedThreshold_ && + (std::abs(currentValue - endValue) <= displacementFromRestThreshold_ || + springStiffness_ == 0); +} + +bool SpringAnimationDriver::isOvershooting(double currentValue) const { + const auto startValue = fromValue_.value(); + return springStiffness_ > 0 && + ((startValue < endValue_ && currentValue > endValue_) || + (startValue > endValue_ && currentValue < endValue_)); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/SpringAnimationDriver.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/SpringAnimationDriver.h new file mode 100644 index 00000000000..e87d222d778 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/drivers/SpringAnimationDriver.h @@ -0,0 +1,50 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "AnimationDriver.h" + +namespace facebook::react { + +class SpringAnimationDriver : public AnimationDriver { + public: + SpringAnimationDriver( + int id, + Tag animatedValueTag, + std::optional endCallback, + const folly::dynamic& config, + NativeAnimatedNodesManager* manager); + + protected: + bool update(double timeDeltaMs, bool restarting) override; + + private: + std::tuple getValueAndVelocityForTime(double time) const; + bool isAtRest(double currentVelocity, double currentValue, double endValue) + const; + bool isOvershooting(double currentValue) const; + + double springStiffness_{0}; + double springDamping_{0}; + double springMass_{0}; + double initialVelocity_{0}; + std::optional fromValue_{std::nullopt}; + double endValue_{0}; + double restSpeedThreshold_{0}; + double displacementFromRestThreshold_{0}; + bool overshootClampingEnabled_{false}; + + double lastTime_{0}; + double timeAccumulator_{0}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/event_drivers/EventAnimationDriver.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/event_drivers/EventAnimationDriver.cpp new file mode 100644 index 00000000000..4023c94c789 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/event_drivers/EventAnimationDriver.cpp @@ -0,0 +1,28 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "EventAnimationDriver.h" + +#include + +namespace facebook::react { + +EventAnimationDriver::EventAnimationDriver( + const std::vector& eventPath, + Tag animatedValueTag) + : eventPath_(eventPath), animatedValueTag_(animatedValueTag) {} + +std::optional EventAnimationDriver::getValueFromPayload( + const EventPayload& eventPayload) { + return eventPayload.extractValue(eventPath_); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/event_drivers/EventAnimationDriver.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/event_drivers/EventAnimationDriver.h new file mode 100644 index 00000000000..53362b9a90b --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/event_drivers/EventAnimationDriver.h @@ -0,0 +1,63 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +class EventAnimationDriver { + public: + EventAnimationDriver( + const std::vector& eventPath, + Tag animatedValueTag); + + ~EventAnimationDriver() = default; + + std::optional getValueFromPayload(const EventPayload& eventPayload); + + Tag getAnimatedNodeTag() const { + return animatedValueTag_; + } + + protected: + std::vector eventPath_; + + Tag animatedValueTag_; +}; + +struct EventAnimationDriverKey { + Tag viewTag; + std::string eventName; + + bool operator==( + const facebook::react::EventAnimationDriverKey& rhs) const noexcept { + return viewTag == rhs.viewTag && eventName == rhs.eventName; + } +}; + +} // namespace facebook::react + +namespace std { +template <> +struct hash { + size_t operator()(const facebook::react::EventAnimationDriverKey& key) const { + return std::hash()(key.viewTag) ^ + std::hash()(key.eventName); + } +}; +} // namespace std diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AdditionAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AdditionAnimatedNode.cpp new file mode 100644 index 00000000000..0facd3d21af --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AdditionAnimatedNode.cpp @@ -0,0 +1,32 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "AdditionAnimatedNode.h" + +#include +#include + +namespace facebook::react { + +void AdditionAnimatedNode::update() { + auto rawValue = 0.0; + if (const auto manager = manager_.lock()) { + for (const auto tag : inputNodes_) { + const auto node = manager->getAnimatedNode(tag); + react_native_assert( + node && "Invalid node tag set as input for AdditionAnimatedNode"); + rawValue += node->value(); + } + } + setRawValue(rawValue); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AdditionAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AdditionAnimatedNode.h new file mode 100644 index 00000000000..53652ef277f --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AdditionAnimatedNode.h @@ -0,0 +1,29 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "ValueAnimatedNode.h" + +namespace facebook::react { + +class AdditionAnimatedNode final : public OperatorAnimatedNode { + public: + AdditionAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : OperatorAnimatedNode(tag, config, manager) {} + + void update() override; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AnimatedNode.cpp new file mode 100644 index 00000000000..e90d0fa325f --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AnimatedNode.cpp @@ -0,0 +1,72 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "AnimatedNode.h" +#include + +#include + +namespace facebook::react { + +AnimatedNode::AnimatedNode( + Tag tag, + folly::dynamic config, + const std::shared_ptr& manager, + AnimatedNodeType type) + : tag_(tag), manager_(manager), type_(type), config_(std::move(config)) {} + +void AnimatedNode::addChild(const Tag animatedNodeTag) { + children_.insert(animatedNodeTag); + getChildNode(animatedNodeTag)->onAttachToNode(tag_); +} + +void AnimatedNode::removeChild(const Tag tag) { + if (const auto childNode = getChildNode(tag)) { + childNode->onDetachedFromNode(tag_); + children_.erase(tag); + } +} + +std::shared_ptr AnimatedNode::getChildNode(Tag tag) { + if (const auto manager = manager_.lock()) { + if (children_.find(tag) != children_.end()) { + return manager->getAnimatedNode(tag); + } + } + + return nullptr; +} + +std::optional AnimatedNode::getNodeTypeByName( + const std::string& nodeTypeName) { + static std::unordered_map typeNames = { + {"style", AnimatedNodeType::Style}, + {"value", AnimatedNodeType::Value}, + {"color", AnimatedNodeType::Color}, + {"props", AnimatedNodeType::Props}, + {"interpolation", AnimatedNodeType::Interpolation}, + {"addition", AnimatedNodeType::Addition}, + {"subtraction", AnimatedNodeType::Subtraction}, + {"division", AnimatedNodeType::Division}, + {"multiplication", AnimatedNodeType::Multiplication}, + {"modulus", AnimatedNodeType::Modulus}, + {"diffclamp", AnimatedNodeType::Diffclamp}, + {"transform", AnimatedNodeType::Transform}, + {"tracking", AnimatedNodeType::Tracking}, + {"round", AnimatedNodeType::Round}}; + + if (auto iter = typeNames.find(nodeTypeName); iter != typeNames.end()) { + return iter->second; + } + return std::nullopt; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AnimatedNode.h new file mode 100644 index 00000000000..2e309dd290e --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/AnimatedNode.h @@ -0,0 +1,110 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include +#include +#include +#include + +namespace facebook::react { + +enum class AnimatedNodeType { + Style, + Value, + Props, + Interpolation, + Addition, + Subtraction, + Division, + Multiplication, + Modulus, + Diffclamp, + Transform, + Tracking, + Color, + Round, +}; + +class NativeAnimatedNodesManager; + +class AnimatedNode { + public: + AnimatedNode( + Tag tag, + folly::dynamic config, + // TODO: T190028913 maybe pass in strongly typed data when constructing + // AnimatedNode + const std::shared_ptr& manager, + AnimatedNodeType type); + + // Detach Node + virtual ~AnimatedNode() = default; + + AnimatedNode(AnimatedNode&&) noexcept = default; + AnimatedNode& operator=(AnimatedNode&&) noexcept = default; + AnimatedNode(const AnimatedNode&) = default; + AnimatedNode& operator=(const AnimatedNode&) = default; + + Tag tag() const { + return tag_; + } + + void addChild(Tag tag); + + void removeChild(Tag tag); + + const std::unordered_set& children() const { + return children_; + } + + AnimatedNodeType type() const { + return type_; + } + + const folly::dynamic& getConfig() const { + return config_; + } + +#ifdef REACT_NATIVE_DEBUG + std::string debugID() const { + return (getConfig().count("debugID") != 0u) + ? getConfig()["debugID"].asString() + : ""; + } +#endif + + virtual void update() {} + + virtual void onDetachedFromNode(Tag /*animatedNodeTag*/) {} + virtual void onAttachToNode(Tag /*animatedNodeTag*/) {} + + static std::optional getNodeTypeByName( + const std::string& nodeTypeName); + + int activeIncomingNodes = 0; + int bfsColor = 0; + + static constexpr int INITIAL_BFS_COLOR = 0; + + protected: + std::shared_ptr getChildNode(Tag tag); + Tag tag_{0}; + std::weak_ptr manager_; + AnimatedNodeType type_; + std::unordered_set children_{}; + + private: + // Should remain unchanged after initialized in constructor + folly::dynamic config_; +}; +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ColorAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ColorAnimatedNode.cpp new file mode 100644 index 00000000000..6c8c2830e17 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ColorAnimatedNode.cpp @@ -0,0 +1,73 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "ColorAnimatedNode.h" +#include +#include + +namespace facebook::react { + +namespace { + +uint8_t getColorValue( + std::shared_ptr manager, + Tag nodeTag, + bool isDecimal = false) { + if (const auto node = manager->getAnimatedNode(nodeTag)) { + if (isDecimal) { + return std::clamp(static_cast(node->value() * 255), 0u, 255u); + } else { + return std::clamp(static_cast(node->value()), 0u, 255u); + } + } + return 0; +} + +uint8_t getAlphaValue( + std::shared_ptr manager, + Tag nodeTag) { + return getColorValue(manager, nodeTag, true); +} + +} // namespace + +ColorAnimatedNode::ColorAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : AnimatedNode(tag, config, manager, AnimatedNodeType::Color), + rNodeTag_(static_cast(getConfig()["r"].asInt())), + gNodeTag_(static_cast(getConfig()["g"].asInt())), + bNodeTag_(static_cast(getConfig()["b"].asInt())), + aNodeTag_(static_cast(getConfig()["a"].asInt())) {} + +void ColorAnimatedNode::update() { + if (const auto manager = manager_.lock()) { + color_ = *colorFromRGBA( + getColorValue(manager, rNodeTag_), + getColorValue(manager, gNodeTag_), + getColorValue(manager, bNodeTag_), + getAlphaValue(manager, aNodeTag_)); + } +} + +Color ColorAnimatedNode::getColor() { + if (const auto manager = manager_.lock()) { + if (manager->updatedNodeTags_.contains(tag_)) { + update(); + manager->updatedNodeTags_.erase(tag_); + } + return color_; + } + return 0; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ColorAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ColorAnimatedNode.h new file mode 100644 index 00000000000..64f3820bf5d --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ColorAnimatedNode.h @@ -0,0 +1,38 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "AnimatedNode.h" + +#include + +namespace facebook::react { +class ColorAnimatedNode final : public AnimatedNode { + public: + ColorAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + + void update() override; + + Color getColor(); + + private: + Tag rNodeTag_{}; + Tag gNodeTag_{}; + Tag bNodeTag_{}; + Tag aNodeTag_{}; + + Color color_{0}; +}; +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DiffClampAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DiffClampAnimatedNode.cpp new file mode 100644 index 00000000000..45f7a141c59 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DiffClampAnimatedNode.cpp @@ -0,0 +1,39 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "DiffClampAnimatedNode.h" + +#include + +namespace facebook::react { + +DiffClampAnimatedNode::DiffClampAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : ValueAnimatedNode(tag, config, manager), + inputNodeTag_(static_cast(getConfig()["input"].asDouble())), + min_(getConfig()["min"].asDouble()), + max_(getConfig()["max"].asDouble()) {} + +void DiffClampAnimatedNode::update() { + if (const auto manager = manager_.lock()) { + if (const auto node = + manager->getAnimatedNode(inputNodeTag_)) { + const auto value = node->value(); + const auto diff = value - lastValue_; + lastValue_ = value; + setRawValue(std::clamp(this->value() + diff, min_, max_)); + } + } +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DiffClampAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DiffClampAnimatedNode.h new file mode 100644 index 00000000000..95d15106a11 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DiffClampAnimatedNode.h @@ -0,0 +1,34 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "ValueAnimatedNode.h" + +namespace facebook::react { + +class DiffClampAnimatedNode final : public ValueAnimatedNode { + public: + DiffClampAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + + void update() override; + + private: + Tag inputNodeTag_; + double min_; + double max_; + double lastValue_{0}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DivisionAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DivisionAnimatedNode.cpp new file mode 100644 index 00000000000..b9f75e14c1c --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DivisionAnimatedNode.cpp @@ -0,0 +1,39 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "DivisionAnimatedNode.h" + +#include +#include + +namespace facebook::react { + +void DivisionAnimatedNode::update() { + auto rawValue = 0.0; + if (const auto manager = manager_.lock()) { + int count = 0; + for (const auto tag : inputNodes_) { + const auto node = manager->getAnimatedNode(tag); + react_native_assert( + node && "Invalid node tag set as input for DivisionAnimatedNode"); + if (count == 0) { + rawValue = node->value(); + } else { + rawValue /= node->value(); + } + + count++; + } + } + setRawValue(rawValue); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DivisionAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DivisionAnimatedNode.h new file mode 100644 index 00000000000..851560b978f --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/DivisionAnimatedNode.h @@ -0,0 +1,29 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "ValueAnimatedNode.h" + +namespace facebook::react { + +class DivisionAnimatedNode final : public OperatorAnimatedNode { + public: + DivisionAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : OperatorAnimatedNode(tag, config, manager) {} + + void update() override; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/InterpolationAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/InterpolationAnimatedNode.cpp new file mode 100644 index 00000000000..2caf8673e46 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/InterpolationAnimatedNode.cpp @@ -0,0 +1,146 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "InterpolationAnimatedNode.h" + +#include +#include +#include +#include + +namespace facebook::react { + +InterpolationAnimatedNode::InterpolationAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : ValueAnimatedNode(tag, config, manager) { + // inputRange example: [0, 1, 10], [1, 1.4, 1.5] + const auto& nodeConfig = getConfig(); + for (const auto& rangeValue : nodeConfig["inputRange"]) { + inputRanges_.push_back(rangeValue.asDouble()); + } + + const bool isColorOutput = nodeConfig["outputType"].isString() && + nodeConfig["outputType"].asString() == "color"; + if (isColorOutput) { + isColorValue_ = true; + for (const auto& rangeValue : nodeConfig["outputRange"]) { + colorOutputRanges_.push_back(static_cast(rangeValue.asInt())); + } + } else { + for (const auto& rangeValue : nodeConfig["outputRange"]) { + defaultOutputRanges_.push_back(rangeValue.asDouble()); + } + } + + extrapolateLeft_ = nodeConfig["extrapolateLeft"].asString(); + extrapolateRight_ = nodeConfig["extrapolateRight"].asString(); +} + +void InterpolationAnimatedNode::update() { + if (parentTag_ == animated::undefinedAnimatedNodeIdentifier) { + return; + } + + if (const auto manager = manager_.lock()) { + if (const auto node = + manager->getAnimatedNode(parentTag_)) { + if (isColorValue_) { + setRawValue(interpolateColor(node->value())); + } else { + setRawValue(interpolateValue(node->value())); + } + } + } +} + +void InterpolationAnimatedNode::onDetachedFromNode(Tag animatedNodeTag) { + assert(parentTag_ == animatedNodeTag); + parentTag_ = animated::undefinedAnimatedNodeIdentifier; +} + +void InterpolationAnimatedNode::onAttachToNode(Tag animatedNodeTag) { + assert(!parentTag_); + parentTag_ = animatedNodeTag; +} + +double InterpolationAnimatedNode::interpolateValue(double value) { + // Compute range index + int index = 1; + for (; index < inputRanges_.size() - 1; ++index) { + if (inputRanges_[index] >= value) { + break; + } + } + index--; + + return interpolate( + value, + inputRanges_[index], + inputRanges_[index + 1], + defaultOutputRanges_[index], + defaultOutputRanges_[index + 1], + extrapolateLeft_, + extrapolateRight_); +} + +double InterpolationAnimatedNode::interpolateColor(double value) { + // Compute range index + int index = 1; + for (; index < inputRanges_.size() - 1; ++index) { + if (inputRanges_[index] >= value) { + break; + } + } + index--; + + const auto outputMin = colorOutputRanges_[index]; + const auto outputMax = colorOutputRanges_[index + 1]; + if (outputMin == outputMax) { + return outputMin; + } + + const auto inputMin = inputRanges_[index]; + const auto inputMax = inputRanges_[index + 1]; + if (inputMin == inputMax) { + if (value <= inputMin) { + return static_cast(outputMin); + } else { + return static_cast(outputMax); + } + } + + auto ratio = (value - inputMin) / (inputMax - inputMin); + + auto outputMinA = alphaFromHostPlatformColor(outputMin); + auto outputMinR = redFromHostPlatformColor(outputMin); + auto outputMinG = greenFromHostPlatformColor(outputMin); + auto outputMinB = blueFromHostPlatformColor(outputMin); + + auto outputMaxA = alphaFromHostPlatformColor(outputMax); + auto outputMaxR = redFromHostPlatformColor(outputMax); + auto outputMaxG = greenFromHostPlatformColor(outputMax); + auto outputMaxB = blueFromHostPlatformColor(outputMax); + + auto outputValueA = ratio * (outputMaxA - outputMinA) + outputMinA; + auto outputValueR = ratio * (outputMaxR - outputMinR) + outputMinR; + auto outputValueG = ratio * (outputMaxG - outputMinG) + outputMinG; + auto outputValueB = ratio * (outputMaxB - outputMinB) + outputMinB; + + return static_cast(hostPlatformColorFromRGBA( + static_cast(outputValueR), + static_cast(outputValueG), + static_cast(outputValueB), + static_cast(outputValueA))); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/InterpolationAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/InterpolationAnimatedNode.h new file mode 100644 index 00000000000..4c45179d9b8 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/InterpolationAnimatedNode.h @@ -0,0 +1,44 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "ValueAnimatedNode.h" + +#include +#include + +namespace facebook::react { + +class InterpolationAnimatedNode final : public ValueAnimatedNode { + public: + InterpolationAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + + void update() override; + void onDetachedFromNode(Tag animatedNodeTag) override; + void onAttachToNode(Tag animatedNodeTag) override; + + private: + double interpolateValue(double value); + double interpolateColor(double value); + + std::vector inputRanges_; + std::vector defaultOutputRanges_; + std::vector colorOutputRanges_; + std::string extrapolateLeft_; + std::string extrapolateRight_; + + Tag parentTag_{animated::undefinedAnimatedNodeIdentifier}; +}; +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ModulusAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ModulusAnimatedNode.cpp new file mode 100644 index 00000000000..a26422a9b0a --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ModulusAnimatedNode.cpp @@ -0,0 +1,35 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "ModulusAnimatedNode.h" + +#include + +namespace facebook::react { + +ModulusAnimatedNode::ModulusAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : ValueAnimatedNode(tag, config, manager), + inputNodeTag_(static_cast(getConfig()["input"].asInt())), + modulus_(getConfig()["modulus"].asDouble()) {} + +void ModulusAnimatedNode::update() { + if (const auto manager = manager_.lock()) { + if (const auto node = + manager->getAnimatedNode(inputNodeTag_)) { + setRawValue(std::fmod(node->value(), modulus_)); + } + } +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ModulusAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ModulusAnimatedNode.h new file mode 100644 index 00000000000..221ec60d606 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ModulusAnimatedNode.h @@ -0,0 +1,32 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "ValueAnimatedNode.h" + +namespace facebook::react { + +class ModulusAnimatedNode final : public ValueAnimatedNode { + public: + ModulusAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + + void update() override; + + private: + Tag inputNodeTag_{}; + double modulus_{}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/MultiplicationAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/MultiplicationAnimatedNode.cpp new file mode 100644 index 00000000000..4cf90835eee --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/MultiplicationAnimatedNode.cpp @@ -0,0 +1,39 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "MultiplicationAnimatedNode.h" + +#include +#include + +namespace facebook::react { + +void MultiplicationAnimatedNode::update() { + auto rawValue = 0.0; + if (const auto manager = manager_.lock()) { + int count = 0; + for (const auto tag : inputNodes_) { + const auto node = manager->getAnimatedNode(tag); + react_native_assert( + node && + "Invalid node tag set as input for MultiplicationAnimatedNode"); + if (count == 0) { + rawValue = node->value(); + } else { + rawValue *= node->value(); + } + count++; + } + } + setRawValue(rawValue); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/MultiplicationAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/MultiplicationAnimatedNode.h new file mode 100644 index 00000000000..a8da00cecdc --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/MultiplicationAnimatedNode.h @@ -0,0 +1,29 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "ValueAnimatedNode.h" + +namespace facebook::react { + +class MultiplicationAnimatedNode final : public OperatorAnimatedNode { + public: + MultiplicationAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : OperatorAnimatedNode(tag, config, manager) {} + + void update() override; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/PropsAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/PropsAnimatedNode.cpp new file mode 100644 index 00000000000..d69a14b9c3a --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/PropsAnimatedNode.cpp @@ -0,0 +1,163 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "PropsAnimatedNode.h" + +#include +#include +#include +#include +#include + +namespace facebook::react { + +namespace { + +bool isLayoutStyleUpdated( + const folly::dynamic& props, + const std::shared_ptr& manager) { + for (const auto& entry : props.items()) { + auto nodeTag = static_cast(entry.second.asInt()); + if (const auto& node = manager->getAnimatedNode(nodeTag)) { + if (node->type() == AnimatedNodeType::Style) { + if (const auto& styleNode = + manager->getAnimatedNode(nodeTag)) { + auto& styleNodeProps = styleNode->getProps(); + for (const auto& styleNodeProp : styleNodeProps.items()) { + if (getDirectManipulationAllowlist().count( + styleNodeProp.first.asString()) == 0u) { + return true; + } + } + } + } + } + } + + return false; +} + +} // namespace + +PropsAnimatedNode::PropsAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : AnimatedNode(tag, config, manager, AnimatedNodeType::Props), + props_(folly::dynamic::object()), + layoutStyleUpdated_(isLayoutStyleUpdated(getConfig()["props"], manager)) { +} + +void PropsAnimatedNode::connectToView(Tag viewTag) { + if (connectedViewTag_) { + throw std::invalid_argument( + "Animated node " + std::to_string(tag_) + + " has already been attached to a view already exists."); + return; + } + connectedViewTag_ = viewTag; +} + +void PropsAnimatedNode::disconnectFromView(Tag viewTag) { + if (connectedViewTag_ == animated::undefinedAnimatedNodeIdentifier) { + return; + } else if (connectedViewTag_ != viewTag) { + throw std::invalid_argument( + "Attempting to disconnect view that has not been connected with the given animated node."); + return; + } + connectedViewTag_ = animated::undefinedAnimatedNodeIdentifier; +} + +// restore the value to whatever the value was on the ShadowNode instead of in +// the View hierarchy +void PropsAnimatedNode::restoreDefaultValues() { + // If node is already disconnected from View, we cannot restore default values + if (connectedViewTag_ != animated::undefinedAnimatedNodeIdentifier) { + if (const auto manager = manager_.lock()) { + manager->schedulePropsCommit( + connectedViewTag_, folly::dynamic::object(), false, false); + } + } +} + +void PropsAnimatedNode::update() { + return update(false); +} + +void PropsAnimatedNode::update(bool forceFabricCommit) { + if (connectedViewTag_ == animated::undefinedAnimatedNodeIdentifier) { + return; + } + + // TODO: T190192206 consolidate shared update logic between + // Props/StyleAnimatedNode + std::lock_guard lock(propsMutex_); + if (const auto manager = manager_.lock()) { + const auto& configProps = getConfig()["props"]; + for (const auto& entry : configProps.items()) { + auto propName = entry.first.asString(); + auto nodeTag = static_cast(entry.second.asInt()); + if (auto node = manager->getAnimatedNode(nodeTag)) { + switch (node->type()) { + case AnimatedNodeType::Value: + case AnimatedNodeType::Interpolation: + case AnimatedNodeType::Modulus: + case AnimatedNodeType::Round: + case AnimatedNodeType::Diffclamp: + // Operators + case AnimatedNodeType::Addition: + case AnimatedNodeType::Subtraction: + case AnimatedNodeType::Multiplication: + case AnimatedNodeType::Division: { + if (const auto& valueNode = + manager->getAnimatedNode(nodeTag)) { + if (valueNode->isColorValue()) { + props_.insert( + propName.c_str(), static_cast(valueNode->value())); + } else { + props_.insert(propName.c_str(), valueNode->value()); + } + } + } break; + case AnimatedNodeType::Color: { + if (const auto& colorNode = + manager->getAnimatedNode(nodeTag)) { + props_.insert( + propName.c_str(), + static_cast(colorNode->getColor())); + } + } break; + case AnimatedNodeType::Style: { + if (const auto& styleNode = + manager->getAnimatedNode(nodeTag)) { + styleNode->update(); + auto& styleNodeProps = styleNode->getProps(); + for (const auto& styleNodeProp : styleNodeProps.items()) { + props_.insert( + styleNodeProp.first.c_str(), styleNodeProp.second); + } + } + } break; + case AnimatedNodeType::Props: + case AnimatedNodeType::Tracking: + case AnimatedNodeType::Transform: + break; + } + } + } + + manager->schedulePropsCommit( + connectedViewTag_, props_, layoutStyleUpdated_, forceFabricCommit); + } +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/PropsAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/PropsAnimatedNode.h new file mode 100644 index 00000000000..e7a494af4f4 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/PropsAnimatedNode.h @@ -0,0 +1,50 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "AnimatedNode.h" + +#include +#include + +namespace facebook::react { +class PropsAnimatedNode final : public AnimatedNode { + public: + PropsAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + void connectToView(Tag viewTag); + void disconnectFromView(Tag viewTag); + void restoreDefaultValues(); + + Tag connectedViewTag() const { + return connectedViewTag_; + } + + folly::dynamic props() { + std::lock_guard lock(propsMutex_); + return props_; + } + + void update() override; + + void update(bool forceFabricCommit); + + private: + std::mutex propsMutex_; + folly::dynamic props_; + const bool layoutStyleUpdated_; + + Tag connectedViewTag_{animated::undefinedAnimatedNodeIdentifier}; +}; +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/RoundAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/RoundAnimatedNode.cpp new file mode 100644 index 00000000000..6bb00b55691 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/RoundAnimatedNode.cpp @@ -0,0 +1,40 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "RoundAnimatedNode.h" + +#include +#include + +namespace facebook::react { + +RoundAnimatedNode::RoundAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : ValueAnimatedNode(tag, config, manager), + inputNodeTag_(static_cast(getConfig()["input"].asInt())), + nearest_(getConfig()["input"].asDouble()) { + react_native_assert( + nearest_ != 0 && + "'nearest' cannot be 0 (can't round to the nearest multiple of 0)"); +} + +void RoundAnimatedNode::update() { + if (auto manager = manager_.lock()) { + auto node = manager->getAnimatedNode(inputNodeTag_); + react_native_assert( + node && "Illegal node ID set as an input for Animated.round node"); + setRawValue(round(node->value() / nearest_) * nearest_); + } +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/RoundAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/RoundAnimatedNode.h new file mode 100644 index 00000000000..7d19b196846 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/RoundAnimatedNode.h @@ -0,0 +1,38 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "ValueAnimatedNode.h" + +#include + +namespace facebook::react { + +/** + * Animated node that rounds the value of another animated node to the nearest + * multiple of a given number. + */ +class RoundAnimatedNode : public ValueAnimatedNode { + public: + RoundAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + + void update() override; + + private: + Tag inputNodeTag_; + double nearest_; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/StyleAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/StyleAnimatedNode.cpp new file mode 100644 index 00000000000..ca7d3fd203d --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/StyleAnimatedNode.cpp @@ -0,0 +1,83 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "StyleAnimatedNode.h" + +#include +#include +#include +#include + +namespace facebook::react { +StyleAnimatedNode::StyleAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : AnimatedNode(tag, config, manager, AnimatedNodeType::Style), + props_(folly::dynamic::object()) {} + +void StyleAnimatedNode::update() { + if (const auto manager = manager_.lock()) { + const auto& style = getConfig()["style"]; + for (const auto& styleProp : style.items()) { + auto propName = styleProp.first.asString(); + const auto nodeTag = static_cast(styleProp.second.asInt()); + if (auto node = manager->getAnimatedNode(nodeTag)) { + switch (node->type()) { + case AnimatedNodeType::Transform: { + if (const auto transformNode = + manager->getAnimatedNode(nodeTag)) { + transformNode->update(); + auto& transformNodeProps = transformNode->getProps(); + for (const auto& styleNodeProp : transformNodeProps.items()) { + props_.insert( + styleNodeProp.first.c_str(), styleNodeProp.second); + } + } + } break; + case AnimatedNodeType::Value: + case AnimatedNodeType::Interpolation: + case AnimatedNodeType::Modulus: + case AnimatedNodeType::Round: + case AnimatedNodeType::Diffclamp: + // Operators + case AnimatedNodeType::Addition: + case AnimatedNodeType::Subtraction: + case AnimatedNodeType::Multiplication: + case AnimatedNodeType::Division: { + if (const auto valueNode = + manager->getAnimatedNode(nodeTag)) { + if (valueNode->isColorValue()) { + props_.insert( + propName.c_str(), static_cast(valueNode->value())); + } else { + props_.insert(propName.c_str(), valueNode->value()); + } + } + } break; + case AnimatedNodeType::Color: { + if (const auto colorAnimNode = + manager->getAnimatedNode(nodeTag)) { + props_.insert( + propName.c_str(), + static_cast(colorAnimNode->getColor())); + } + } break; + case AnimatedNodeType::Tracking: + case AnimatedNodeType::Style: + case AnimatedNodeType::Props: + break; + } + } + } + } +} +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/StyleAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/StyleAnimatedNode.h new file mode 100644 index 00000000000..90fcf32920a --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/StyleAnimatedNode.h @@ -0,0 +1,34 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "AnimatedNode.h" + +#include + +namespace facebook::react { +class StyleAnimatedNode final : public AnimatedNode { + public: + StyleAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + void update() override; + + const folly::dynamic& getProps() const { + return props_; + } + + private: + folly::dynamic props_; +}; +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/SubtractionAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/SubtractionAnimatedNode.cpp new file mode 100644 index 00000000000..6b3e4aa1d76 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/SubtractionAnimatedNode.cpp @@ -0,0 +1,39 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "SubtractionAnimatedNode.h" + +#include +#include + +namespace facebook::react { + +void SubtractionAnimatedNode::update() { + auto rawValue = 0.0; + if (const auto manager = manager_.lock()) { + int count = 0; + for (const auto& tag : inputNodes_) { + const auto node = manager->getAnimatedNode(tag); + react_native_assert( + node && "Invalid node tag set as input for SubtractionAnimatedNode"); + if (count == 0) { + rawValue = node->value(); + } else { + rawValue -= node->value(); + } + + count++; + } + } + setRawValue(rawValue); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/SubtractionAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/SubtractionAnimatedNode.h new file mode 100644 index 00000000000..71c02a51666 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/SubtractionAnimatedNode.h @@ -0,0 +1,30 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include +#include "ValueAnimatedNode.h" + +namespace facebook::react { + +class SubtractionAnimatedNode final : public OperatorAnimatedNode { + public: + SubtractionAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : OperatorAnimatedNode(tag, config, manager) {} + + void update() override; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TrackingAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TrackingAnimatedNode.cpp new file mode 100644 index 00000000000..ac31c98aa06 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TrackingAnimatedNode.cpp @@ -0,0 +1,45 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "TrackingAnimatedNode.h" + +#include +#include + +namespace facebook::react { + +TrackingAnimatedNode::TrackingAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : AnimatedNode(tag, config, manager, AnimatedNodeType::Tracking), + animationId_(static_cast(getConfig()["animationId"].asInt())), + toValueNodeId_(static_cast(getConfig()["toValue"].asInt())), + valueNodeId_(static_cast(getConfig()["value"].asInt())) {} + +void TrackingAnimatedNode::update() { + if (const auto manager = manager_.lock()) { + if (const auto toValueNode = + manager->getAnimatedNode(toValueNodeId_)) { + // In case the animation is already running, we need to stop it to free up + // the animationId key in the active animations map in the animation + // manager. + manager->stopAnimation(animationId_, true); + auto animationConfig = getConfig()["animationConfig"]; + animationConfig["toValue"] = toValueNode->value(); + + manager->startAnimatingNode( + animationId_, valueNodeId_, animationConfig, std::nullopt); + } + } +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TrackingAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TrackingAnimatedNode.h new file mode 100644 index 00000000000..1738841d391 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TrackingAnimatedNode.h @@ -0,0 +1,33 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "AnimatedNode.h" + +namespace facebook::react { + +class TrackingAnimatedNode final : public AnimatedNode { + public: + TrackingAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + + void update() override; + + private: + int animationId_{}; + Tag toValueNodeId_{}; // Value node to be tracked + Tag valueNodeId_{}; // Value node to be updated +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TransformAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TransformAnimatedNode.cpp new file mode 100644 index 00000000000..e0805f06952 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TransformAnimatedNode.cpp @@ -0,0 +1,65 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "TransformAnimatedNode.h" + +#include +#include +#include +#include + +namespace facebook::react { + +static constexpr std::string_view sTransformsName{"transforms"}; +static constexpr std::string_view sPropertyName{"property"}; +static constexpr std::string_view sTypeName{"type"}; +static constexpr std::string_view sAnimatedName{"animated"}; +static constexpr std::string_view sNodeTagName{"nodeTag"}; +static constexpr std::string_view sValueName{"value"}; +static constexpr std::string_view sTransformPropName{"transform"}; + +TransformAnimatedNode::TransformAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : AnimatedNode(tag, config, manager, AnimatedNodeType::Transform), + props_(folly::dynamic::object()) {} + +void TransformAnimatedNode::update() { + folly::dynamic transforms = folly::dynamic::array(); + if (const auto manager = manager_.lock()) { + auto transformsArray = getConfig()[sTransformsName]; + react_native_assert(transformsArray.type() == folly::dynamic::ARRAY); + for (const auto& transform : transformsArray) { + std::optional value; + if (transform[sTypeName].asString() == sAnimatedName) { + const auto inputTag = static_cast(transform[sNodeTagName].asInt()); + if (const auto node = + manager->getAnimatedNode(inputTag)) { + value = node->value(); + } + } else { + value = transform[sValueName].asDouble(); + } + if (value) { + const auto property = transform[sPropertyName].asString(); + transforms.push_back(folly::dynamic::object(property, value.value())); + } + } + props_[sTransformPropName] = std::move(transforms); + } +} + +const folly::dynamic& TransformAnimatedNode::getProps() { + return props_; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TransformAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TransformAnimatedNode.h new file mode 100644 index 00000000000..727fe283651 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/TransformAnimatedNode.h @@ -0,0 +1,39 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "AnimatedNode.h" + +namespace facebook::react { + +struct TransformConfig { + public: + std::string property; + Tag nodeTag; + double value; +}; + +class TransformAnimatedNode final : public AnimatedNode { + public: + TransformAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + + void update() override; + + const folly::dynamic& getProps(); + + private: + folly::dynamic props_; +}; +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ValueAnimatedNode.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ValueAnimatedNode.cpp new file mode 100644 index 00000000000..69a0081f06d --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ValueAnimatedNode.cpp @@ -0,0 +1,102 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#include "ValueAnimatedNode.h" + +#include +#include + +namespace facebook::react { +ValueAnimatedNode::ValueAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : AnimatedNode(tag, config, manager, AnimatedNodeType::Value) { + auto value = 0.0; + auto offset = 0.0; + if ((getConfig().count("value") != 0u) && + (getConfig().count("offset") != 0u)) { + value = getConfig()["value"].asDouble(); + offset = getConfig()["offset"].asDouble(); + } + + value_ = value; + offset_ = offset; +} + +bool ValueAnimatedNode::setRawValue(double value) { + if (value_ != value) { + value_ = value; + + onValueUpdate(); + return true; + } + return false; +} + +double ValueAnimatedNode::rawValue() { + return value_; +} + +double ValueAnimatedNode::offset() { + return offset_; +} + +bool ValueAnimatedNode::setOffset(double offset) { + if (offset_ != offset) { + offset_ = offset; + + onValueUpdate(); + return true; + } + return true; +} + +double ValueAnimatedNode::value() { + return value_ + offset(); +} + +void ValueAnimatedNode::flattenOffset() { + setRawValue(value_ + offset()); + setOffset(0.0f); +} + +void ValueAnimatedNode::extractOffset() { + setOffset(value_ + offset()); + setRawValue(0.0f); +} + +void ValueAnimatedNode::onValueUpdate() { + if (valueListener_) { + valueListener_(value()); + } +} + +void ValueAnimatedNode::setValueListener(ValueListenerCallback&& callback) { + valueListener_ = std::move(callback); +} + +OperatorAnimatedNode::OperatorAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager) + : ValueAnimatedNode(tag, config, manager) { + const auto& input = getConfig()["input"]; + react_native_assert( + input.type() == folly::dynamic::ARRAY && input.size() >= 2); + + for (const auto& inputNode : input) { + const auto inputTag = static_cast(inputNode.asInt()); + inputNodes_.push_back(inputTag); + } +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ValueAnimatedNode.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ValueAnimatedNode.h new file mode 100644 index 00000000000..6073229928a --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/nodes/ValueAnimatedNode.h @@ -0,0 +1,63 @@ +/* + * 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. + */ + +/* + * Adapted from react-native-windows under the MIT license. + */ + +#pragma once + +#include "AnimatedNode.h" + +#include + +namespace facebook::react { + +using ValueListenerCallback = std::function; + +class ValueAnimatedNode : public AnimatedNode { + public: + ValueAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + double value(); + double rawValue(); + bool setRawValue(double value); + double offset(); + bool setOffset(double offset); + void flattenOffset(); + void extractOffset(); + void setValueListener(ValueListenerCallback&& callback); + + virtual bool isColorValue() { + return isColorValue_; + } + + protected: + bool isColorValue_{false}; + + private: + void onValueUpdate(); + + double value_{0.0}; + double offset_{0.0}; + ValueListenerCallback valueListener_{}; +}; + +class OperatorAnimatedNode : public ValueAnimatedNode { + public: + OperatorAnimatedNode( + Tag tag, + const folly::dynamic& config, + const std::shared_ptr& manager); + + protected: + std::vector inputNodes_{}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/primitives.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/primitives.h new file mode 100644 index 00000000000..1be452a2199 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/primitives.h @@ -0,0 +1,16 @@ +/* + * 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. + */ + +#pragma once +#include + +namespace facebook::react::animated { +// Indicates that the animated node identifier is not defined. +// It is safe to use 0 because JavaScript starts assigning identifiers from 1. +// https://github.com/facebook/react-native/blob/main/packages/react-native/src/private/animated/NativeAnimatedHelper.js#L35 +constexpr static Tag undefinedAnimatedNodeIdentifier = 0; +} // namespace facebook::react::animated diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/AnimatedNodeTests.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/AnimatedNodeTests.cpp new file mode 100644 index 00000000000..81be3ef3882 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/AnimatedNodeTests.cpp @@ -0,0 +1,219 @@ +/* + * 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. + */ + +#include "AnimationTestsBase.h" + +#include +#include +#include + +namespace facebook::react { + +class AnimatedNodeTests : public AnimationTestsBase {}; + +TEST_F(AnimatedNodeTests, setAnimatedNodeValue) { + initNodesManager(); + + auto rootTag = getNextRootViewTag(); + auto animatedNodeTag = ++rootTag; + nodesManager_->createAnimatedNode( + animatedNodeTag, + folly::dynamic::object("type", "value")("value", 0)("offset", 5)); + const auto node = + nodesManager_->getAnimatedNode(animatedNodeTag); + EXPECT_EQ(nodeNeedsUpdate(animatedNodeTag), true); + + runAnimationFrame(0); + EXPECT_EQ(nodeNeedsUpdate(animatedNodeTag), false); + + nodesManager_->setAnimatedNodeValue(animatedNodeTag, 100); + // ValueAnimatedNode will immediately update value, before Animated updates + // dirtied nodes at next frame + EXPECT_EQ(nodesManager_->getValue(animatedNodeTag), 105); + + EXPECT_EQ(nodeNeedsUpdate(animatedNodeTag), true); + + runAnimationFrame(0); + EXPECT_EQ(nodeNeedsUpdate(animatedNodeTag), false); + + nodesManager_->dropAnimatedNode(animatedNodeTag); +} + +TEST_F(AnimatedNodeTests, updatePropsNode) { + initNodesManager(); + + // Step 1: Build the Nodes graph + auto rootTag = getNextRootViewTag(); + + // Create ColorNode + auto rTag = ++rootTag; + auto gTag = ++rootTag; + auto bTag = ++rootTag; + auto aTag = ++rootTag; + auto colorNodeTag = ++rootTag; + nodesManager_->createAnimatedNode( + rTag, folly::dynamic::object("type", "value")("value", 0)("offset", 0)); + nodesManager_->createAnimatedNode( + gTag, folly::dynamic::object("type", "value")("value", 255)("offset", 0)); + nodesManager_->createAnimatedNode( + bTag, folly::dynamic::object("type", "value")("value", 0)("offset", 0)); + nodesManager_->createAnimatedNode( + aTag, folly::dynamic::object("type", "value")("value", 0.5)("offset", 0)); + nodesManager_->createAnimatedNode( + colorNodeTag, + folly::dynamic::object("type", "color")("r", rTag)("g", gTag)("b", bTag)( + "a", aTag)); + nodesManager_->connectAnimatedNodes(rTag, colorNodeTag); + nodesManager_->connectAnimatedNodes(gTag, colorNodeTag); + nodesManager_->connectAnimatedNodes(bTag, colorNodeTag); + nodesManager_->connectAnimatedNodes(aTag, colorNodeTag); + + // Create opacity ValueNode + auto opacityNodeTag = ++rootTag; + nodesManager_->createAnimatedNode( + opacityNodeTag, + folly::dynamic::object("type", "value")("value", 0.8f)("offset", 0)); + + // Create StyleNode + auto styleNodeTag = ++rootTag; + nodesManager_->createAnimatedNode( + styleNodeTag, + folly::dynamic::object("type", "style")( + "style", + folly::dynamic::object("backgroundColor", colorNodeTag)( + "opacity", opacityNodeTag))); + + nodesManager_->connectAnimatedNodes(colorNodeTag, styleNodeTag); + nodesManager_->connectAnimatedNodes(opacityNodeTag, styleNodeTag); + + // Create PropsNode + auto propsNodeTag = ++rootTag; + nodesManager_->createAnimatedNode( + propsNodeTag, + folly::dynamic::object("type", "props")( + "props", folly::dynamic::object("style", styleNodeTag))); + nodesManager_->connectAnimatedNodes(styleNodeTag, propsNodeTag); + + // Connect PropsNode to View + auto viewTag = ++rootTag; + nodesManager_->connectAnimatedNodeToView(propsNodeTag, viewTag); + + runAnimationFrame(0); + + // Step 2: Update backgroundColor + { + nodesManager_->setAnimatedNodeValue(bTag, 100); + nodesManager_->setAnimatedNodeValue(aTag, 0.3); + + // Confirm the nodes graph is correctly marked dirty + EXPECT_EQ(nodeNeedsUpdate(rTag), false); + EXPECT_EQ(nodeNeedsUpdate(gTag), false); + EXPECT_EQ(nodeNeedsUpdate(bTag), true); + EXPECT_EQ(nodeNeedsUpdate(aTag), true); + EXPECT_EQ(nodeNeedsUpdate(opacityNodeTag), false); + // connected style/prop nodes are not marked dirty but they will be updated + // at next render + EXPECT_EQ(nodeNeedsUpdate(styleNodeTag), false); + EXPECT_EQ(nodeNeedsUpdate(propsNodeTag), false); + + // Flush changes + runAnimationFrame(0); + + // Check props commit done via MountingManager + auto color = + static_cast(lastCommittedProps["backgroundColor"].asInt()); + EXPECT_EQ(redFromColor({color}), 0); + EXPECT_EQ(greenFromColor({color}), 255); + EXPECT_EQ(blueFromColor({color}), 100); + EXPECT_EQ(alphaFromColor({color}), static_cast(0.3 * 255)); + EXPECT_EQ(lastUpdatedNodeTag, viewTag); + } + + // Step 3: Update opacity + { + nodesManager_->setAnimatedNodeValue(opacityNodeTag, 0.1f); + + // Confirm the nodes graph is correctly marked dirty + EXPECT_EQ(nodeNeedsUpdate(rTag), false); + EXPECT_EQ(nodeNeedsUpdate(gTag), false); + EXPECT_EQ(nodeNeedsUpdate(bTag), false); + EXPECT_EQ(nodeNeedsUpdate(aTag), false); + EXPECT_EQ(nodeNeedsUpdate(opacityNodeTag), true); + // connected style/prop nodes are not marked dirty but they will be updated + // at next render + EXPECT_EQ(nodeNeedsUpdate(styleNodeTag), false); + EXPECT_EQ(nodeNeedsUpdate(propsNodeTag), false); + + // Flush changes + runAnimationFrame(0); + + // Check props commit done via MountingManager + EXPECT_EQ(lastCommittedProps["opacity"], 0.1f); + EXPECT_EQ(lastUpdatedNodeTag, viewTag); + } +} + +TEST_F(AnimatedNodeTests, ModulusAnimatedNode) { + initNodesManager(); + + auto rootTag = getNextRootViewTag(); + + auto valueTag = ++rootTag; + auto moduloTag = ++rootTag; + + nodesManager_->createAnimatedNode( + valueTag, + folly::dynamic::object("type", "value")("value", 0)("offset", 1)); + nodesManager_->createAnimatedNode( + moduloTag, + folly::dynamic::object("type", "modulus")("input", valueTag)( + "modulus", 3.1)); + nodesManager_->connectAnimatedNodes(valueTag, moduloTag); + + runAnimationFrame(0); + + nodesManager_->setAnimatedNodeValue(valueTag, 4.1); + + runAnimationFrame(0); + + EXPECT_EQ(nodesManager_->getValue(valueTag), 5.1); + EXPECT_EQ(nodesManager_->getValue(moduloTag), std::fmod(5.1, 3.1)); + + nodesManager_->setAnimatedNodeValue(valueTag, 7.6); + + runAnimationFrame(0); + + EXPECT_EQ(nodesManager_->getValue(valueTag), 8.6); + EXPECT_EQ(nodesManager_->getValue(moduloTag), std::fmod(8.6, 3.1)); +} + +TEST_F(AnimatedNodeTests, DiffClampAnimatedNode) { + initNodesManager(); + + auto rootTag = getNextRootViewTag(); + + auto valueTag = ++rootTag; + auto diffClampTag = ++rootTag; + + nodesManager_->createAnimatedNode( + valueTag, + folly::dynamic::object("type", "value")("value", 4)("offset", 0)); + nodesManager_->createAnimatedNode( + diffClampTag, + folly::dynamic::object("type", "diffclamp")("input", valueTag)("min", 1)( + "max", 2)); + nodesManager_->connectAnimatedNodes(valueTag, diffClampTag); + + runAnimationFrame(0); + EXPECT_EQ(nodesManager_->getValue(diffClampTag), 2); + + nodesManager_->setAnimatedNodeValue(valueTag, 2); + runAnimationFrame(0); + EXPECT_EQ(nodesManager_->getValue(diffClampTag), 1); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/AnimationDriverTests.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/AnimationDriverTests.cpp new file mode 100644 index 00000000000..456edf22943 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/AnimationDriverTests.cpp @@ -0,0 +1,61 @@ +/* + * 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. + */ + +#include "AnimationTestsBase.h" + +#include +#include + +namespace facebook::react { + +class AnimationDriverTests : public AnimationTestsBase { + protected: + double round(double value) noexcept { + // Round to 2 decimal places + return std::ceil(value * 100) / 100; + } +}; + +TEST_F(AnimationDriverTests, framesAnimation) { + initNodesManager(); + + auto rootTag = getNextRootViewTag(); + + auto valueNodeTag = ++rootTag; + nodesManager_->createAnimatedNode( + valueNodeTag, + folly::dynamic::object("type", "value")("value", 0)("offset", 0)); + + const auto animationId = 1; + const auto frames = folly::dynamic::array(0.0f, 0.1f, 0.4f, 0.9f, 1.0f); + const auto toValue = 100; + nodesManager_->startAnimatingNode( + animationId, + valueNodeTag, + folly::dynamic::object("type", "frames")("frames", frames)( + "toValue", toValue), + std::nullopt); + + const auto startTimeInTick = 12345; + + runAnimationFrame(startTimeInTick); + EXPECT_EQ(round(nodesManager_->getValue(valueNodeTag).value()), 0); + + runAnimationFrame(startTimeInTick + SingleFrameIntervalMs * 2.5 * TicksPerMs); + EXPECT_EQ(round(nodesManager_->getValue(valueNodeTag).value()), 65); + + runAnimationFrame(startTimeInTick + SingleFrameIntervalMs * 3 * TicksPerMs); + EXPECT_EQ(round(nodesManager_->getValue(valueNodeTag).value()), 90); + + runAnimationFrame(startTimeInTick + SingleFrameIntervalMs * 4 * TicksPerMs); + EXPECT_EQ(round(nodesManager_->getValue(valueNodeTag).value()), toValue); + + runAnimationFrame(startTimeInTick + SingleFrameIntervalMs * 10 * TicksPerMs); + EXPECT_EQ(round(nodesManager_->getValue(valueNodeTag).value()), toValue); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/AnimationTestsBase.h b/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/AnimationTestsBase.h new file mode 100644 index 00000000000..8e582908b55 --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/AnimationTestsBase.h @@ -0,0 +1,53 @@ +/* + * 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. + */ + +#pragma once + +#ifdef _WIN32 +#include +#include +#endif + +#include +#include + +namespace facebook::react { + +class AnimationTestsBase : public testing::Test { + public: + AnimationTestsBase() = default; + + protected: + void initNodesManager() noexcept { + nodesManager_.reset(); + nodesManager_ = std::make_shared( + [this](Tag reactTag, const folly::dynamic& changedProps) { + lastUpdatedNodeTag = reactTag; + lastCommittedProps = changedProps; + }, + [this](const std::unordered_map& nodesProps) { + if (!nodesProps.empty()) { + lastUpdatedNodeTag = nodesProps.begin()->first; + lastCommittedProps = nodesProps.begin()->second; + } + }); + } + + bool nodeNeedsUpdate(Tag nodeTag) const { + return nodesManager_->updatedNodeTags_.contains(nodeTag); + } + + void runAnimationFrame(double timestamp) { + nodesManager_->onAnimationFrame(static_cast(timestamp)); + } + + std::shared_ptr nodesManager_; + folly::dynamic lastCommittedProps{folly::dynamic::object()}; + Tag lastUpdatedNodeTag{}; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/EventAnimationDriverTests.cpp b/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/EventAnimationDriverTests.cpp new file mode 100644 index 00000000000..149807fcacd --- /dev/null +++ b/packages/react-native/ReactCxxPlatform/react/renderer/animated/tests/EventAnimationDriverTests.cpp @@ -0,0 +1,71 @@ +/* + * 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. + */ + +#include "AnimationTestsBase.h" + +#include +#include +#include + +namespace facebook::react { + +class EventAnimationDriverTests : public AnimationTestsBase {}; + +TEST_F(EventAnimationDriverTests, subscribeToViewEvent) { + initNodesManager(); + + auto tag = getNextRootViewTag(); + + auto viewTag = ++tag; + const auto animatedValueTag = ++tag; + const auto animatedValueTag2 = ++tag; + + const auto eventName = "scroll"; + + const folly::dynamic valueNodeConfig = + folly::dynamic::object("type", "value")("value", 0)("offset", 0); + + // Call onRender once to initialize thread local + nodesManager_->onRender(); + + { + nodesManager_->createAnimatedNode(animatedValueTag, valueNodeConfig); + + folly::dynamic eventMapping = + folly::dynamic::object("animatedValueTag", animatedValueTag)( + "nativeEventPath", folly::dynamic::array("contentOffset", "y")); + nodesManager_->addAnimatedEventToView(viewTag, eventName, eventMapping); + } + + { + nodesManager_->createAnimatedNode(animatedValueTag2, valueNodeConfig); + + folly::dynamic eventMapping = + folly::dynamic::object("animatedValueTag", animatedValueTag2)( + "nativeEventPath", folly::dynamic::array("zoomScale")); + nodesManager_->addAnimatedEventToView(viewTag, eventName, eventMapping); + } + + EXPECT_EQ(nodesManager_->getValue(animatedValueTag), 0); + EXPECT_EQ(nodesManager_->getValue(animatedValueTag2), 0); + + auto scrollEvent = std::make_shared(); + scrollEvent->contentSize = {1, 2}; + scrollEvent->contentOffset = {3, 4}; + scrollEvent->contentInset = {5, 6, 7, 8}; + scrollEvent->containerSize = {9, 10}; + scrollEvent->zoomScale = 11.0f; + + const std::string eventType{eventName}; + const SharedEventPayload payload = scrollEvent; + (*nodesManager_->getEventEmitterListener())(viewTag, eventName, *scrollEvent); + + EXPECT_EQ(nodesManager_->getValue(animatedValueTag), 4); + EXPECT_EQ(nodesManager_->getValue(animatedValueTag2), 11); +} + +} // namespace facebook::react