diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateShadowTree.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateShadowTree.cpp index 50e6e545d626..1833b5e6f35b 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateShadowTree.cpp +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateShadowTree.cpp @@ -7,82 +7,16 @@ #include "UIManager.h" -#include -#include #include #include #include #include -#include -#include +#include namespace facebook::react { -namespace { - -struct ShadowNodeUpdateInfo { - Tag tag; - int depth; - std::weak_ptr node; - // populate for node that needs props update - std::optional changedProps{}; - // populate for node that's also a ancestor node for updated nodes - std::vector updatedChildrenIndices{}; -}; - -void addAncestorsToUpdateList( - std::shared_ptr& shadowNode, - std::shared_ptr& rootShadowNode, - std::vector& shadowNodesToUpdate) { - // list of ancestors from root ShadowNode to current ShadowNode's parent - auto ancestors = shadowNode->getFamily().getAncestors(*rootShadowNode); - - std::vector> ancestorShadowNodesShared{}; - ancestorShadowNodesShared.resize(ancestors.size()); - std::shared_ptr currentShadowNode = rootShadowNode; - auto ancestorIndex = 0; - while (!currentShadowNode->getChildren().empty() && - currentShadowNode->getTag() != shadowNode->getTag()) { - ancestorShadowNodesShared[ancestorIndex] = currentShadowNode; - const auto& children = currentShadowNode->getChildren(); - auto childIndex = ancestors[ancestorIndex].second; - currentShadowNode = children[childIndex]; - ancestorIndex++; - } - - int ancestorDepth = static_cast(ancestors.size() - 1); - // iterate from current ShadowNode's parent to root ShadowNode - for (auto iter = ancestors.rbegin(); iter != ancestors.rend(); ++iter) { - auto& ancestorShadowNode = iter->first.get(); - auto ancestorTag = ancestorShadowNode.getTag(); - auto ancestorAddedToUpdateList = std::find_if( - shadowNodesToUpdate.begin(), - shadowNodesToUpdate.end(), - [ancestorTag](const auto& elem) { return elem.tag == ancestorTag; }); - if (ancestorAddedToUpdateList == shadowNodesToUpdate.end()) { - react_native_assert( - ancestorShadowNodesShared[ancestorDepth]->getTag() == - ancestorShadowNode.getTag()); - shadowNodesToUpdate.push_back({ - .tag = ancestorShadowNode.getTag(), - .depth = ancestorDepth, - .node = ancestorShadowNodesShared[ancestorDepth], - .updatedChildrenIndices = {iter->second}, - }); - } else { - ancestorAddedToUpdateList->updatedChildrenIndices.push_back(iter->second); - } - ancestorDepth--; - } -} - -} // namespace - /* Commit a map of ShadowNode props to ShadowTree, with guarantee that each * ShadowNode is cloned only once in the commit. - * The tree cloning algorithm is inspired by `cloneShadowTreeWithNewProps` in - * https://github.com/software-mansion/react-native-reanimated/ (under MIT - * license). */ void UIManager::updateShadowTree( std::unordered_map&& tagToProps) { @@ -103,133 +37,69 @@ void UIManager::updateShadowTree( auto rootShadowNode = shadowTree.getCurrentRevision().rootShadowNode; auto surfaceId = rootShadowNode->getSurfaceId(); - std::vector shadowNodesToUpdate; - // Step 1: Create a list of shadow nodes to update - // which includes all the ShadowNodes of tags in input map, plus all - // their ancestors + // Step 1: Find the families of the tags in this surface, and take their + // props out of the remaining map. + + std::unordered_set> families; + std::unordered_map surfaceTagToProps; std::deque> deque{rootShadowNode}; - int depth = 0; - while (!deque.empty()) { - auto size = deque.size(); - for (auto i = 0; i < size; i++) { - auto shadowNode = std::move(deque.front()); - deque.pop_front(); - - if (auto nodesPropsIt = remainingTagToProps.find(shadowNode->getTag()); - nodesPropsIt != remainingTagToProps.end()) { - auto shadowNodeTag = shadowNode->getTag(); - auto shadowNodeAddedToUpdateList = std::find_if( - shadowNodesToUpdate.begin(), - shadowNodesToUpdate.end(), - [shadowNodeTag](const auto& elem) { - return elem.tag == shadowNodeTag; - }); - if (shadowNodeAddedToUpdateList == shadowNodesToUpdate.end()) { - shadowNodesToUpdate.push_back( - {.tag = shadowNodeTag, - .depth = depth, - .node = shadowNode, - .changedProps = nodesPropsIt->second}); - } else { - shadowNodeAddedToUpdateList->changedProps = nodesPropsIt->second; - } - remainingTagToProps.erase(nodesPropsIt->first); - - // Add all its ancestors to shadowNodesToUpdate list - addAncestorsToUpdateList( - shadowNode, rootShadowNode, shadowNodesToUpdate); - - // Every node and its ancestors are in the list, so the rest of the - // tree does not need to be visited. - if (remainingTagToProps.empty()) { - deque.clear(); - break; - } - } - for (const auto& child : shadowNode->getChildren()) { - deque.push_back(child); - } - } - depth++; - } + // Every node is found once the map is empty, so the rest of the tree does + // not need to be visited. + while (!deque.empty() && !remainingTagToProps.empty()) { + auto shadowNode = std::move(deque.front()); + deque.pop_front(); - if (shadowNodesToUpdate.empty()) { - return; - } + if (auto nodeHandle = remainingTagToProps.extract(shadowNode->getTag())) { + families.insert(shadowNode->getFamilyShared()); + surfaceTagToProps.insert(std::move(nodeHandle)); + } - // Step 2: Clone nodes from children to ancestors - - std::sort( - shadowNodesToUpdate.begin(), - shadowNodesToUpdate.end(), - [](const auto& a, const auto& b) { return a.depth > b.depth; }); - - std::unordered_map> clonedShadowNodes; - - for (auto& nodeUpdateInfo : shadowNodesToUpdate) { - if (auto oldShadowNode = nodeUpdateInfo.node.lock()) { - Props::Shared newProps; - if (nodeUpdateInfo.changedProps) { - PropsParserContext propsParserContext{surfaceId, contextContainer}; - auto componentDescriptor = - componentDescriptorRegistry_ - ->findComponentDescriptorByHandle_DO_NOT_USE_THIS_IS_BROKEN( - oldShadowNode->getComponentHandle()); - newProps = componentDescriptor->cloneProps( - propsParserContext, - oldShadowNode->getProps(), - RawProps(nodeUpdateInfo.changedProps.value())); - } else { - newProps = oldShadowNode->getProps(); - } - - ShadowNodeFragment fragment; - auto children = oldShadowNode->getChildren(); - - // If children are previously updated (children should be cloned and - // updated before parents), add it to the children list of ShadowNode - for (auto& updatedChildIndex : nodeUpdateInfo.updatedChildrenIndices) { - if (updatedChildIndex < children.size()) { - auto childTag = children[updatedChildIndex]->getTag(); - auto clonedShadowNodesIt = clonedShadowNodes.find(childTag); - if (clonedShadowNodesIt != clonedShadowNodes.end()) { - children[updatedChildIndex] = clonedShadowNodesIt->second; - } else { - LOG(ERROR) << "Child ShadowNode has not been cloned"; - } - } else { - LOG(WARNING) << "Child no longer exits"; - } - } - - auto cloned = oldShadowNode->clone( - {.props = newProps, - .children = std::make_shared< - std::vector>>( - std::move(children))}); - clonedShadowNodes.insert({oldShadowNode->getTag(), std::move(cloned)}); - } else { - LOG(ERROR) << "oldShadowNode is null"; - continue; + for (const auto& child : shadowNode->getChildren()) { + deque.push_back(child); } } - // Step 3: Commit ShadowTree - - if (auto it = clonedShadowNodes.find(rootShadowNode->getTag()); - it != clonedShadowNodes.end()) { - shadowTree.commit( - [rootNode = - it->second](const RootShadowNode&) -> RootShadowNode::Unshared { - return std::static_pointer_cast(rootNode); - }, - {}); - } else { - LOG(ERROR) << "Root ShadowNode has not been cloned"; + if (families.empty()) { + return; } + + // Step 2: Clone the nodes and their ancestors, and commit. + // + // Clone the root that the transaction receives, not `rootShadowNode`. + // Another thread can commit between the walk above and this commit (for + // example, `SurfaceHandler::constraintLayout` after the surface is + // resized, or a native state update). Returning a tree cloned from + // `rootShadowNode` would silently revert that commit, and retrying the + // transaction would not help because it would return the same tree. + + shadowTree.commit( + [&](const RootShadowNode& oldRootShadowNode) + -> RootShadowNode::Unshared { + return std::static_pointer_cast( + oldRootShadowNode.cloneMultiple( + families, + [&](const ShadowNode& oldShadowNode, + const ShadowNodeFragment& fragment) { + auto newProps = ShadowNodeFragment::propsPlaceholder(); + if (auto propsIt = + surfaceTagToProps.find(oldShadowNode.getTag()); + propsIt != surfaceTagToProps.end()) { + PropsParserContext propsParserContext{ + surfaceId, contextContainer}; + newProps = + oldShadowNode.getComponentDescriptor().cloneProps( + propsParserContext, + oldShadowNode.getProps(), + RawProps(propsIt->second)); + } + return oldShadowNode.clone( + {.props = newProps, .children = fragment.children}); + })); + }, + {}); }); } diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/tests/UIManagerUpdateShadowTreeTest.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/tests/UIManagerUpdateShadowTreeTest.cpp new file mode 100644 index 000000000000..d37b01100773 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/tests/UIManagerUpdateShadowTreeTest.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 +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +namespace { + +// Commits `concurrentCommit` from another thread the first time a commit +// reaches the hooks, and waits for it. The commit that reached the hooks has +// already run its transaction, so this is what happens when another thread +// commits while that transaction runs: its revision check fails and the +// transaction runs again on the newer tree. +class InterleavingCommitHook : public UIManagerCommitHook { + public: + explicit InterleavingCommitHook(std::function concurrentCommit) + : concurrentCommit_(std::move(concurrentCommit)) {} + + void commitHookWasRegistered( + const UIManager& /*uiManager*/) noexcept override {} + void commitHookWasUnregistered( + const UIManager& /*uiManager*/) noexcept override {} + + RootShadowNode::Unshared shadowTreeWillCommit( + const ShadowTree& /*shadowTree*/, + const RootShadowNode::Shared& /*oldRootShadowNode*/, + const RootShadowNode::Unshared& newRootShadowNode, + const ShadowTreeCommitOptions& /*commitOptions*/) noexcept override { + if (concurrentCommit_ && std::this_thread::get_id() == ownerThreadId_) { + auto concurrentCommit = std::move(concurrentCommit_); + concurrentCommit_ = nullptr; + std::thread(concurrentCommit).join(); + } + return newRootShadowNode; + } + + private: + std::function concurrentCommit_; + std::thread::id ownerThreadId_{std::this_thread::get_id()}; +}; + +} // namespace + +class UIManagerUpdateShadowTreeTest : public ::testing::Test { + public: + UIManagerUpdateShadowTreeTest() { + contextContainer_ = std::make_shared(); + + ComponentDescriptorProviderRegistry componentDescriptorProviderRegistry{}; + auto componentDescriptorRegistry = + componentDescriptorProviderRegistry.createComponentDescriptorRegistry( + ComponentDescriptorParameters{ + .eventDispatcher = EventDispatcher::Shared{}, + .contextContainer = contextContainer_, + .flavor = nullptr}); + + componentDescriptorProviderRegistry.add( + concreteComponentDescriptorProvider()); + componentDescriptorProviderRegistry.add( + concreteComponentDescriptorProvider()); + + builder_ = std::make_unique(componentDescriptorRegistry); + + RuntimeExecutor runtimeExecutor = + [](std::function&& /*callback*/) {}; + uiManager_ = + std::make_unique(runtimeExecutor, contextContainer_); + uiManager_->setComponentDescriptorRegistry(componentDescriptorRegistry); + + buildAndCommitTree(); + } + + void TearDown() override { + uiManager_->stopSurface(surfaceId_); + } + + protected: + void buildAndCommitTree() { + std::shared_ptr rootNode; + + // clang-format off + auto element = + Element() + .tag(1) + .surfaceId(surfaceId_) + .reference(rootNode) + .props([this] { + auto sharedProps = std::make_shared(); + sharedProps->layoutConstraints = initialLayoutConstraints_; + return sharedProps; + }) + .children({ + Element() + .tag(animatedViewTag_) + .surfaceId(surfaceId_) + .props([] { + auto sharedProps = std::make_shared(); + sharedProps->opacity = 1.0; + return sharedProps; + }), + Element() + .tag(siblingViewTag_) + .surfaceId(surfaceId_) + .props([] { + auto sharedProps = std::make_shared(); + sharedProps->nativeId = "initial"; + return sharedProps; + }) + }); + // clang-format on + + builder_->build(element); + + auto shadowTree = std::make_unique( + surfaceId_, + initialLayoutConstraints_, + LayoutContext{}, + *uiManager_, + *contextContainer_); + + shadowTreePtr_ = shadowTree.get(); + + shadowTree->commit( + [&rootNode](const RootShadowNode& /*oldRootShadowNode*/) { + return std::static_pointer_cast(rootNode); + }, + {true}); + + uiManager_->startSurface( + std::move(shadowTree), + "test", + folly::dynamic::object, + DisplayMode::Visible); + } + + // What `SurfaceHandler::constraintLayout` commits when the surface is + // resized. + void commitLayoutConstraints(const LayoutConstraints& layoutConstraints) { + shadowTreePtr_->commit( + [&](const RootShadowNode& oldRootShadowNode) { + PropsParserContext propsParserContext{surfaceId_, *contextContainer_}; + return oldRootShadowNode.clone( + propsParserContext, layoutConstraints, LayoutContext{}); + }, + {}); + } + + std::shared_ptr currentRoot() const { + return shadowTreePtr_->getCurrentRevision().rootShadowNode; + } + + // The root's children are `[animatedView, siblingView]`. + const ViewProps& viewPropsInTree(Tag tag) const { + const auto& children = currentRoot()->getChildren(); + const auto& child = + tag == animatedViewTag_ ? children.front() : children.back(); + EXPECT_EQ(child->getTag(), tag); + return static_cast(*child->getProps()); + } + + SurfaceId surfaceId_{0}; + Tag animatedViewTag_{42}; + Tag siblingViewTag_{43}; + LayoutConstraints initialLayoutConstraints_{ + .minimumSize = {.width = 0, .height = 0}, + .maximumSize = {.width = 500, .height = 800}}; + std::shared_ptr contextContainer_; + std::unique_ptr builder_; + std::unique_ptr uiManager_; + ShadowTree* shadowTreePtr_{nullptr}; +}; + +TEST_F(UIManagerUpdateShadowTreeTest, UpdatesProps) { + uiManager_->updateShadowTree( + {{animatedViewTag_, folly::dynamic::object("opacity", 0.5)}}); + + EXPECT_FLOAT_EQ(viewPropsInTree(animatedViewTag_).opacity, 0.5); + EXPECT_EQ(viewPropsInTree(siblingViewTag_).nativeId, "initial"); +} + +TEST_F(UIManagerUpdateShadowTreeTest, IgnoresTagsNotInTree) { + auto rootBefore = currentRoot(); + + uiManager_->updateShadowTree( + {{1234, folly::dynamic::object("opacity", 0.5)}}); + + EXPECT_EQ(currentRoot(), rootBefore); +} + +// The surface is resized (fold, rotation, split screen) while +// `updateShadowTree` commits props for a native-driven animation. +TEST_F( + UIManagerUpdateShadowTreeTest, + KeepsLayoutConstraintsCommittedConcurrently) { + auto resizedLayoutConstraints = LayoutConstraints{ + .minimumSize = {.width = 0, .height = 0}, + .maximumSize = {.width = 800, .height = 500}}; + + InterleavingCommitHook commitHook{ + [&] { commitLayoutConstraints(resizedLayoutConstraints); }}; + uiManager_->registerCommitHook(commitHook); + auto unregisterCommitHook = + OnScopeExit([&]() { uiManager_->unregisterCommitHook(commitHook); }); + + uiManager_->updateShadowTree( + {{animatedViewTag_, folly::dynamic::object("opacity", 0.5)}}); + + EXPECT_EQ( + currentRoot()->getConcreteProps().layoutConstraints, + resizedLayoutConstraints); + EXPECT_FLOAT_EQ(viewPropsInTree(animatedViewTag_).opacity, 0.5); +} + +TEST_F(UIManagerUpdateShadowTreeTest, KeepsNodesCommittedConcurrently) { + InterleavingCommitHook commitHook{[&] { + shadowTreePtr_->commit( + [&](const RootShadowNode& oldRootShadowNode) { + auto& siblingFamily = + oldRootShadowNode.getChildren().back()->getFamily(); + return std::static_pointer_cast( + oldRootShadowNode.cloneTree( + siblingFamily, [&](const ShadowNode& oldShadowNode) { + PropsParserContext propsParserContext{ + surfaceId_, *contextContainer_}; + return oldShadowNode.clone( + {.props = + oldShadowNode.getComponentDescriptor().cloneProps( + propsParserContext, + oldShadowNode.getProps(), + RawProps( + folly::dynamic::object( + "nativeID", "concurrent")))}); + })); + }, + {}); + }}; + uiManager_->registerCommitHook(commitHook); + auto unregisterCommitHook = + OnScopeExit([&]() { uiManager_->unregisterCommitHook(commitHook); }); + + uiManager_->updateShadowTree( + {{animatedViewTag_, folly::dynamic::object("opacity", 0.5)}}); + + EXPECT_EQ(viewPropsInTree(siblingViewTag_).nativeId, "concurrent"); + EXPECT_FLOAT_EQ(viewPropsInTree(animatedViewTag_).opacity, 0.5); +} + +} // namespace facebook::react