diff --git a/packages/react-native/Libraries/ReactNative/__tests__/SyncOnCommit-itest.js b/packages/react-native/Libraries/ReactNative/__tests__/SyncOnCommit-itest.js index faada0aa8f3..cd0cfebe74a 100644 --- a/packages/react-native/Libraries/ReactNative/__tests__/SyncOnCommit-itest.js +++ b/packages/react-native/Libraries/ReactNative/__tests__/SyncOnCommit-itest.js @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @fantom_flags updateRuntimeShadowNodeReferencesOnCommit:true + * @fantom_flags updateRuntimeShadowNodeReferencesOnCommit:true enableFabricCommitBranching:* * @fantom_react_fb_flags passChildrenWhenCloningPersistedNodes:true * @flow strict-local * @format diff --git a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.cpp b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.cpp index 680ba595be4..a3ac0b0effe 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.cpp @@ -49,4 +49,36 @@ void NativeFantomTestSpecificMethods::takeFunctionAndNoop( jsi::Runtime& runtime, jsi::Function function) {} +void NativeFantomTestSpecificMethods::setRootNodeSize( + jsi::Runtime& runtime, + int surfaceId, + float width, + float height) { + auto& uiManager = getUIManagerFromRuntime(runtime); + + uiManager.getShadowTreeRegistry().visit( + surfaceId, [&](const ShadowTree& shadowTree) { + shadowTree.commit( + [&](const RootShadowNode& oldRootShadowNode) + -> RootShadowNode::Unshared { + PropsParserContext propsParserContext{ + surfaceId, *uiManager.getContextContainer()}; + + const auto& mainBranchRootProps = + oldRootShadowNode.getConcreteProps(); + const auto layoutContext = mainBranchRootProps.layoutContext; + auto layoutConstraints = mainBranchRootProps.layoutConstraints; + + layoutConstraints.maximumSize.width = width; + layoutConstraints.maximumSize.height = height; + layoutConstraints.minimumSize.width = width; + layoutConstraints.minimumSize.height = height; + + return oldRootShadowNode.clone( + propsParserContext, layoutConstraints, layoutContext); + }, + {.source = ShadowTreeCommitSource::Unknown}); + }); +} + } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h index a82fa536122..aff0dbf4fc9 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h +++ b/packages/react-native/ReactCommon/react/nativemodule/fantomtestspecificmethods/NativeFantomTestSpecificMethods.h @@ -21,6 +21,8 @@ class NativeFantomTestSpecificMethods : public NativeFantomTestSpecificMethodsCx void takeFunctionAndNoop(jsi::Runtime &runtime, jsi::Function callback); + void setRootNodeSize(jsi::Runtime &runtime, int surfaceId, float width, float height); + private: std::shared_ptr fantomForcedCloneCommitHook_{}; }; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.cpp b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.cpp index 58c5bbaa4e0..ec806e3be22 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.cpp @@ -220,7 +220,7 @@ void ShadowTree::setCommitMode(CommitMode commitMode) const { auto revision = ShadowTreeRevision{}; { - ShadowTree::UniqueLock lock = uniqueCommitLock(); + ShadowTree::UniqueLock lock = uniqueRevisionLock(); if (commitMode_ == commitMode) { return; @@ -238,7 +238,7 @@ void ShadowTree::setCommitMode(CommitMode commitMode) const { } CommitMode ShadowTree::getCommitMode() const { - SharedLock lock = sharedCommitLock(); + SharedLock lock = sharedRevisionLock(); return commitMode_; } @@ -262,7 +262,7 @@ CommitStatus ShadowTree::commit( } { - std::unique_lock lock(commitMutexRecursive_); + std::unique_lock lock(revisionMutexRecursive_); return tryCommit(transaction, commitOptions); } } else { @@ -286,18 +286,32 @@ CommitStatus ShadowTree::tryCommit( const CommitOptions& commitOptions) const { TraceSection s("ShadowTree::commit"); + auto isReactBranch = ReactNativeFeatureFlags::enableFabricCommitBranching() && + commitOptions.source == CommitSource::React; + + // Commits on the JS branch are never synchronous. + react_native_assert(!isReactBranch || !commitOptions.mountSynchronously); + auto telemetry = TransactionTelemetry{}; telemetry.willCommit(); CommitMode commitMode; auto oldRevision = ShadowTreeRevision{}; + auto oldRevisionForStateProgression = ShadowTreeRevision{}; auto newRevision = ShadowTreeRevision{}; { // Reading `currentRevision_` in shared manner. - SharedLock lock = sharedCommitLock(); + SharedLock lock = sharedRevisionLock(); commitMode = commitMode_; - oldRevision = currentRevision_; + + if (isReactBranch && currentReactRevision_.has_value()) { + oldRevision = currentReactRevision_.value(); + } else { + oldRevision = currentRevision_; + } + + oldRevisionForStateProgression = currentRevision_; } const auto& oldRootShadowNode = oldRevision.rootShadowNode; @@ -308,8 +322,8 @@ CommitStatus ShadowTree::tryCommit( } if (commitOptions.enableStateReconciliation) { - auto updatedNewRootShadowNode = - progressState(*newRootShadowNode, *oldRootShadowNode); + auto updatedNewRootShadowNode = progressState( + *newRootShadowNode, *oldRevisionForStateProgression.rootShadowNode); if (updatedNewRootShadowNode) { newRootShadowNode = std::static_pointer_cast(updatedNewRootShadowNode); @@ -336,9 +350,10 @@ CommitStatus ShadowTree::tryCommit( { // Updating `currentRevision_` in unique manner if it hasn't changed. - UniqueLock lock = uniqueCommitLock(); + UniqueLock lock = uniqueRevisionLock( + /*defer*/ isReactBranch); - if (currentRevision_.number != oldRevision.number) { + if (!isReactBranch && currentRevision_.number != oldRevision.number) { return CommitStatus::Failed; } @@ -364,12 +379,21 @@ CommitStatus ShadowTree::tryCommit( .number = newRevisionNumber, .telemetry = telemetry}; - currentRevision_ = newRevision; + if (isReactBranch) { + // Lock the deferred lock to ensure that the new React revision is not + // reset during a scheduled merge. + std::visit([](auto& concreteLock) { concreteLock.lock(); }, lock); + currentReactRevision_ = newRevision; + } else { + currentRevision_ = newRevision; + } } emitLayoutEvents(affectedLayoutableNodes); - if (commitMode == CommitMode::Normal) { + if (isReactBranch) { + scheduleReactRevisionPromotion(); + } else if (commitMode == CommitMode::Normal) { mount(std::move(newRevision), commitOptions.mountSynchronously); } @@ -377,10 +401,15 @@ CommitStatus ShadowTree::tryCommit( } ShadowTreeRevision ShadowTree::getCurrentRevision() const { - SharedLock lock = sharedCommitLock(); + SharedLock lock = sharedRevisionLock(); return currentRevision_; } +std::optional ShadowTree::getCurrentReactRevision() const { + SharedLock lock = sharedRevisionLock(); + return currentReactRevision_; +} + void ShadowTree::mount(ShadowTreeRevision revision, bool mountSynchronously) const { mountingCoordinator_->push(std::move(revision)); @@ -388,6 +417,72 @@ void ShadowTree::mount(ShadowTreeRevision revision, bool mountSynchronously) mountingCoordinator_, mountSynchronously); } +void ShadowTree::mergeReactRevision() const { + ShadowTreeRevision promotedRevision; + + { + UniqueLock lock = uniqueRevisionLock(false); + + if (!reactRevisionToBePromoted_.has_value()) { + return; + } + + promotedRevision = + std::exchange(reactRevisionToBePromoted_, std::nullopt).value(); + } + + const auto mergedRevisionNumber = promotedRevision.number; + + this->commit( + [revision = std::move(promotedRevision)]( + const RootShadowNode& /*oldRootShadowNode*/) { + return std::make_shared( + *revision.rootShadowNode, ShadowNodeFragment{}); + }, + { + .enableStateReconciliation = true, + .mountSynchronously = true, + .source = CommitSource::ReactRevisionMerge, + }); + + { + UniqueLock commitLock = uniqueRevisionLock( + /*defer*/ false); + + // If the current react revision is the same as the one that was just + // merged, clear it. + if (currentReactRevision_.has_value() && + mergedRevisionNumber == currentReactRevision_.value().number) { + currentReactRevision_.reset(); + } + } +} + +void ShadowTree::promoteReactRevision() const { + ShadowTreeRevision currentReactRevision; + { + SharedLock lock = sharedRevisionLock(); + // Promotion happens at the end of the event loop tick, it's possible to + // have more than one promotion in a row. In this case, all but the first + // one should no-op. + if (!currentReactRevision_.has_value()) { + return; + } + currentReactRevision = currentReactRevision_.value(); + } + + { + UniqueLock lock = uniqueRevisionLock(false); + reactRevisionToBePromoted_ = std::move(currentReactRevision); + } + + delegate_.shadowTreeDidPromoteReactRevision(*this); +} + +void ShadowTree::scheduleReactRevisionPromotion() const { + delegate_.shadowTreeDidFinishReactCommit(*this); +} + void ShadowTree::commitEmptyTree() const { commit( [](const RootShadowNode& oldRootShadowNode) @@ -426,19 +521,21 @@ void ShadowTree::notifyDelegatesOfUpdates() const { delegate_.shadowTreeDidFinishTransaction(mountingCoordinator_, true); } -inline ShadowTree::UniqueLock ShadowTree::uniqueCommitLock() const { +inline ShadowTree::UniqueLock ShadowTree::uniqueRevisionLock(bool defer) const { if (ReactNativeFeatureFlags::preventShadowTreeCommitExhaustion()) { - return std::unique_lock{commitMutexRecursive_}; + return defer ? std::unique_lock{revisionMutexRecursive_, std::defer_lock} + : std::unique_lock{revisionMutexRecursive_}; } else { - return std::unique_lock{commitMutex_}; + return defer ? std::unique_lock{revisionMutex_, std::defer_lock} + : std::unique_lock{revisionMutex_}; } } -inline ShadowTree::SharedLock ShadowTree::sharedCommitLock() const { +inline ShadowTree::SharedLock ShadowTree::sharedRevisionLock() const { if (ReactNativeFeatureFlags::preventShadowTreeCommitExhaustion()) { - return std::unique_lock{commitMutexRecursive_}; + return std::unique_lock{revisionMutexRecursive_}; } else { - return std::shared_lock{commitMutex_}; + return std::shared_lock{revisionMutex_}; } } diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h index c1f51fc1a91..b97680b8c25 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h @@ -51,6 +51,7 @@ enum class ShadowTreeCommitSource { Unknown, React, AnimationEndSync, + ReactRevisionMerge, }; struct ShadowTreeCommitOptions { @@ -124,6 +125,12 @@ class ShadowTree final { */ ShadowTreeRevision getCurrentRevision() const; + /* + * Returns a `ShadowTreeRevision` representing the momentary state of + * the `ShadowTree` in the JS thread. + */ + std::optional getCurrentReactRevision() const; + /* * Commit an empty tree (a new `RootShadowNode` with no children). */ @@ -137,6 +144,18 @@ class ShadowTree final { std::shared_ptr getMountingCoordinator() const; + /** + * Promotes the current React revision to be merged into the main branch of the + * ShadowTree. + */ + void promoteReactRevision() const; + + /** + * Commits the currently promoted React revision to the "main" branch of the + * ShadowTree. No-op if the promoted React revision doesn't exist. + */ + void mergeReactRevision() const; + private: constexpr static ShadowTreeRevision::Number INITIAL_REVISION{0}; @@ -144,19 +163,23 @@ class ShadowTree final { void emitLayoutEvents(std::vector &affectedLayoutableNodes) const; + void scheduleReactRevisionPromotion() const; + const SurfaceId surfaceId_; const ShadowTreeDelegate &delegate_; - mutable std::shared_mutex commitMutex_; - mutable std::recursive_mutex commitMutexRecursive_; - mutable CommitMode commitMode_{CommitMode::Normal}; // Protected by `commitMutex_`. - mutable ShadowTreeRevision currentRevision_; // Protected by `commitMutex_`. + mutable std::shared_mutex revisionMutex_; + mutable std::recursive_mutex revisionMutexRecursive_; + mutable CommitMode commitMode_{CommitMode::Normal}; // Protected by `revisionMutex_`. + mutable ShadowTreeRevision currentRevision_; // Protected by `revisionMutex_`. + mutable std::optional currentReactRevision_; // Protected by `revisionMutex_`. + mutable std::optional reactRevisionToBePromoted_; // Protected by `revisionMutex_`. std::shared_ptr mountingCoordinator_; using UniqueLock = std::variant, std::unique_lock>; using SharedLock = std::variant, std::unique_lock>; - inline UniqueLock uniqueCommitLock() const; - inline SharedLock sharedCommitLock() const; + inline UniqueLock uniqueRevisionLock(bool defer = false) const; + inline SharedLock sharedRevisionLock() const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h index 650d898a6f3..3dde9c5837c 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTreeDelegate.h @@ -38,6 +38,17 @@ class ShadowTreeDelegate { std::shared_ptr mountingCoordinator, bool mountSynchronously) const = 0; + /* + * Called right after Shadow Tree commits a new React revision of the tree. + */ + virtual void shadowTreeDidFinishReactCommit(const ShadowTree &shadowTree) const = 0; + + /* + * Called right after Shadow Tree promotes a React revision of the tree to + * be merged. + */ + virtual void shadowTreeDidPromoteReactRevision(const ShadowTree &shadowTree) const = 0; + virtual ~ShadowTreeDelegate() noexcept = default; }; diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/tests/StateReconciliationTest.cpp b/packages/react-native/ReactCommon/react/renderer/mounting/tests/StateReconciliationTest.cpp index 7290d76cc63..721a46700be 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/tests/StateReconciliationTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mounting/tests/StateReconciliationTest.cpp @@ -37,6 +37,12 @@ class DummyShadowTreeDelegate : public ShadowTreeDelegate { void shadowTreeDidFinishTransaction( std::shared_ptr mountingCoordinator, bool /*mountSynchronously*/) const override {} + + void shadowTreeDidFinishReactCommit( + const ShadowTree& /*shadowTree*/) const override {} + + void shadowTreeDidPromoteReactRevision( + const ShadowTree& /*shadowTree*/) const override {} }; namespace { diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp index bf0e3d93a04..af2a59f0a28 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp @@ -366,6 +366,21 @@ void Scheduler::uiManagerShouldRemoveEventListener( removeEventListener(listener); } +void Scheduler::uiManagerDidFinishReactCommit(const ShadowTree& shadowTree) { + auto surfaceId = shadowTree.getSurfaceId(); + runtimeScheduler_->scheduleRenderingUpdate( + surfaceId, [surfaceId, uiManager = uiManager_]() { + uiManager->getShadowTreeRegistry().visit( + surfaceId, + [](const ShadowTree& tree) { tree.promoteReactRevision(); }); + }); +} + +void Scheduler::uiManagerDidPromoteReactRevision(const ShadowTree& shadowTree) { + // Replaced by scheduling on the UI thread in the following diff. + shadowTree.mergeReactRevision(); +} + void Scheduler::uiManagerDidStartSurface(const ShadowTree& shadowTree) { std::shared_lock lock(onSurfaceStartCallbackMutex_); if (onSurfaceStartCallback_) { diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h index 80be380a48e..080c5407c13 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h @@ -95,6 +95,8 @@ class Scheduler final : public UIManagerDelegate { void uiManagerDidUpdateShadowTree(const std::unordered_map &tagToProps) override; void uiManagerShouldAddEventListener(std::shared_ptr listener) final; void uiManagerShouldRemoveEventListener(const std::shared_ptr &listener) final; + void uiManagerDidFinishReactCommit(const ShadowTree &shadowTree) override; + void uiManagerDidPromoteReactRevision(const ShadowTree &shadowTree) override; void uiManagerDidStartSurface(const ShadowTree &shadowTree) override; #pragma mark - ContextContainer diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp index 8dddd3ced43..1239c8a73f7 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp @@ -644,6 +644,20 @@ void UIManager::shadowTreeDidFinishTransaction( } } +void UIManager::shadowTreeDidFinishReactCommit( + const ShadowTree& shadowTree) const { + if (delegate_ != nullptr) { + delegate_->uiManagerDidFinishReactCommit(shadowTree); + } +} + +void UIManager::shadowTreeDidPromoteReactRevision( + const ShadowTree& shadowTree) const { + if (delegate_ != nullptr) { + delegate_->uiManagerDidPromoteReactRevision(shadowTree); + } +} + void UIManager::reportMount(SurfaceId surfaceId) const { TraceSection s("UIManager::reportMount"); @@ -718,6 +732,12 @@ void UIManager::synchronouslyUpdateViewOnUIThread( } } +#pragma mark ContextContainer + +std::shared_ptr UIManager::getContextContainer() const { + return contextContainer_; +} + #pragma mark - Add & Remove event listener void UIManager::addEventListener( diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h index eac4b5d9a49..bb287fe40f2 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h @@ -135,6 +135,10 @@ class UIManager final : public ShadowTreeDelegate { const RootShadowNode::Unshared &newRootShadowNode, const ShadowTree::CommitOptions &commitOptions) const override; + void shadowTreeDidFinishReactCommit(const ShadowTree &shadowTree) const override; + + void shadowTreeDidPromoteReactRevision(const ShadowTree &shadowTree) const override; + std::shared_ptr createNode( Tag tag, const std::string &componentName, @@ -201,6 +205,9 @@ class UIManager final : public ShadowTreeDelegate { void updateShadowTree(std::unordered_map &&tagToProps); +#pragma mark - ContextContainer + std::shared_ptr getContextContainer() const; + #pragma mark - Add & Remove event listener void addEventListener(std::shared_ptr listener); diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h index 32df5c92f10..92ee339f092 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerDelegate.h @@ -84,6 +84,16 @@ class UIManagerDelegate { */ virtual void uiManagerDidStartSurface(const ShadowTree &shadowTree) = 0; + /* + * Called after a new React revision of the shadow tree is committed. + */ + virtual void uiManagerDidFinishReactCommit(const ShadowTree &shadowTree) = 0; + + /* + * Called after a React revision of the shadow tree is promoted to be merged. + */ + virtual void uiManagerDidPromoteReactRevision(const ShadowTree &shadowTree) = 0; + using OnSurfaceStartCallback = std::function; virtual void uiManagerShouldSetOnSurfaceStartCallback(OnSurfaceStartCallback &&callback) = 0; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.cpp index 8afaad89b39..cf11c7f9d28 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.cpp @@ -24,7 +24,9 @@ LazyShadowTreeRevisionConsistencyManager::updateCurrentRevision( // root shadow nodes concurrently. RootShadowNode::Shared rootShadowNode; shadowTreeRegistry_.visit(surfaceId, [&](const ShadowTree& shadowTree) { - rootShadowNode = shadowTree.getCurrentRevision().rootShadowNode; + auto reactRevision = shadowTree.getCurrentReactRevision(); + rootShadowNode = + reactRevision.value_or(shadowTree.getCurrentRevision()).rootShadowNode; }); std::unique_lock lock(capturedRootShadowNodesForConsistencyMutex_); diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h b/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h index b63ec2977db..c7ab5af7fac 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/LazyShadowTreeRevisionConsistencyManager.h @@ -13,7 +13,6 @@ #include #include #include -#include namespace facebook::react { diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/tests/LazyShadowTreeRevisionConsistencyManagerTest.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/tests/LazyShadowTreeRevisionConsistencyManagerTest.cpp index 322172b3de1..349a79f3d49 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/tests/LazyShadowTreeRevisionConsistencyManagerTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/consistency/tests/LazyShadowTreeRevisionConsistencyManagerTest.cpp @@ -27,6 +27,12 @@ class FakeShadowTreeDelegate : public ShadowTreeDelegate { void shadowTreeDidFinishTransaction( std::shared_ptr mountingCoordinator, bool /*mountSynchronously*/) const override {} + + void shadowTreeDidFinishReactCommit( + const ShadowTree& /*shadowTree*/) const override {} + + void shadowTreeDidPromoteReactRevision( + const ShadowTree& /*shadowTree*/) const override {} }; class LazyShadowTreeRevisionConsistencyManagerTest : public ::testing::Test { diff --git a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp index 7affd88dca0..74427d2a72b 100644 --- a/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp +++ b/packages/react-native/ReactCxxPlatform/react/runtime/ReactHost.cpp @@ -311,6 +311,9 @@ void ReactHost::destroyReactInstance() { reactInstanceData_->contextContainer->erase(RuntimeSchedulerKey); reactInstanceData_->mountingManager->setSchedulerTaskExecutor(nullptr); + reactInstanceData_->mountingManager = nullptr; + reactInstanceData_->contextContainer = nullptr; + reactInstanceData_->turboModuleProviders.clear(); reactInstance_ = nullptr; reactInstanceData_->messageQueueThread = nullptr; } diff --git a/packages/react-native/src/private/__tests__/utilities/__tests__/ShadowNodeReferenceCounter-itest.js b/packages/react-native/src/private/__tests__/utilities/__tests__/ShadowNodeReferenceCounter-itest.js index 5bb74b14601..00112dd2900 100644 --- a/packages/react-native/src/private/__tests__/utilities/__tests__/ShadowNodeReferenceCounter-itest.js +++ b/packages/react-native/src/private/__tests__/utilities/__tests__/ShadowNodeReferenceCounter-itest.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @fantom_flags enableFabricCommitBranching:* * @flow strict-local * @format */ diff --git a/packages/react-native/src/private/__tests__/utilities/__tests__/ShadowNodeRevisionGetter-itest.js b/packages/react-native/src/private/__tests__/utilities/__tests__/ShadowNodeRevisionGetter-itest.js index 3475f0cb385..f5bd1e3bfbd 100644 --- a/packages/react-native/src/private/__tests__/utilities/__tests__/ShadowNodeRevisionGetter-itest.js +++ b/packages/react-native/src/private/__tests__/utilities/__tests__/ShadowNodeRevisionGetter-itest.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @fantom_flags enableFabricCommitBranching:* * @flow strict-local * @format */ diff --git a/packages/react-native/src/private/renderer/branching/__tests__/ShadowTreeBranching-itest.js b/packages/react-native/src/private/renderer/branching/__tests__/ShadowTreeBranching-itest.js new file mode 100644 index 00000000000..d37fa968119 --- /dev/null +++ b/packages/react-native/src/private/renderer/branching/__tests__/ShadowTreeBranching-itest.js @@ -0,0 +1,252 @@ +/** + * 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. + * + * @fantom_flags enableFabricCommitBranching:true + * @flow strict-local + * @format + */ + +import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; + +import type {HostInstance} from 'react-native'; + +import ensureInstance from '../../../__tests__/utilities/ensureInstance'; +import * as Fantom from '@react-native/fantom'; +import * as React from 'react'; +import {View} from 'react-native'; +import NativeFantomTestSpecificMethods from 'react-native/src/private/testing/fantom/specs/NativeFantomTestSpecificMethods'; +import ReactNativeElement from 'react-native/src/private/webapis/dom/nodes/ReactNativeElement'; + +describe('ShadowTreeBranching', () => { + function LayoutEffectObserver({onCommit}: {onCommit: () => void}) { + React.useLayoutEffect(() => { + onCommit(); + }); + return null; + } + + it('should not mount React revision before merging them', () => { + const root = Fantom.createRoot(); + + Fantom.runTask(() => { + root.render(); + }); + + expect(root.takeMountingManagerLogs()).toEqual([ + 'Update {type: "RootView", nativeID: (root)}', + 'Create {type: "View", nativeID: "view"}', + 'Insert {type: "View", parentNativeID: (root), index: 0, nativeID: "view"}', + ]); + + let updatesBeforeEndOfTask: $ReadOnlyArray = []; + + Fantom.runTask(() => { + root.render( + <> + + { + updatesBeforeEndOfTask = root.takeMountingManagerLogs(); + }} + /> + , + ); + }); + + const updatesAfterEndOfTask = root.takeMountingManagerLogs(); + + // The intermediate React revision should not be mounted + expect(updatesBeforeEndOfTask).toEqual([]); + expect(updatesAfterEndOfTask).toEqual([ + 'Update {type: "View", nativeID: "view"}', + ]); + }); + + it('should not skip intermediate React commits', () => { + const root = Fantom.createRoot(); + + let updatesBeforeEndOfTask: $ReadOnlyArray = []; + + // When rendered with `shouldTriggerIntermediate=false`, it renders two views + // both with blue background. When rendered with `shouldTriggerIntermediate=true`, + // it renders two views, the first one with red background and the second one + // with blue background. The layout effect will update the second view to red. + // The intermediate React revision with different background colors should not + // be committed. + function AutoUpdateComponent({ + shouldTriggerIntermediate, + }: { + shouldTriggerIntermediate: boolean, + }) { + const [intermediateRender, setIntermediateRender] = React.useState(false); + + return ( + + + + { + if (shouldTriggerIntermediate) { + if (!intermediateRender) { + setIntermediateRender(true); + return; + } + + updatesBeforeEndOfTask = root.takeMountingManagerLogs(); + } + }} + /> + + ); + } + + Fantom.runTask(() => { + root.render(); + }); + + expect(root.takeMountingManagerLogs()).toEqual([ + 'Update {type: "RootView", nativeID: (root)}', + 'Create {type: "View", nativeID: "view"}', + 'Create {type: "View", nativeID: "A"}', + 'Create {type: "View", nativeID: "B"}', + 'Insert {type: "View", parentNativeID: "view", index: 0, nativeID: "A"}', + 'Insert {type: "View", parentNativeID: "view", index: 1, nativeID: "B"}', + 'Insert {type: "View", parentNativeID: (root), index: 0, nativeID: "view"}', + ]); + + Fantom.runTask(() => { + root.render(); + }); + + const updatesAfterEndOfTask = root.takeMountingManagerLogs(); + + // The intermediate React revision should not be committed + expect(updatesBeforeEndOfTask).toEqual([]); + expect(updatesAfterEndOfTask).toEqual([ + 'Update {type: "View", nativeID: "A"}', + 'Update {type: "View", nativeID: "B"}', + ]); + }); + + it('should provide up-to-date data when read from JS', () => { + const root = Fantom.createRoot(); + + const viewRef = React.createRef(); + + Fantom.runTask(() => { + root.render( + , + ); + }); + + expect(root.takeMountingManagerLogs()).toEqual([ + 'Update {type: "RootView", nativeID: (root)}', + 'Create {type: "View", nativeID: "view"}', + 'Insert {type: "View", parentNativeID: (root), index: 0, nativeID: "view"}', + ]); + + let dimensions: [number, number] = [0, 0]; + let mountingManagerLogs: Array = []; + + Fantom.runTask(() => { + root.render( + <> + + { + mountingManagerLogs = root.takeMountingManagerLogs(); + + // The React revision is not merged yet but the new dimensions + // should be visible from JS + const viewNode = ensureInstance( + viewRef.current, + ReactNativeElement, + ); + const rect = viewNode.getBoundingClientRect(); + dimensions = [rect.width, rect.height]; + }} + /> + , + ); + }); + + expect(mountingManagerLogs).toEqual([]); + expect(dimensions).toEqual([50, 50]); + }); + + it('should not mount intermediate React tree when committing from another source', () => { + const root = Fantom.createRoot(); + + const viewRef = React.createRef(); + + Fantom.runTask(() => { + root.render( + , + ); + }); + + expect(root.takeMountingManagerLogs()).toEqual([ + 'Update {type: "RootView", nativeID: (root)}', + 'Create {type: "View", nativeID: "view"}', + 'Insert {type: "View", parentNativeID: (root), index: 0, nativeID: "view"}', + ]); + + let mountingManagerLogsBeforeEndOfTask: Array = []; + + Fantom.runTask(() => { + root.render( + <> + + { + NativeFantomTestSpecificMethods.setRootNodeSize( + root.getRootTag() as $FlowFixMe, + 150, + 150, + ); + + mountingManagerLogsBeforeEndOfTask = + root.takeMountingManagerLogs(); + }} + /> + , + ); + }); + + // Commit made from outside of React - it should not mount intermediate React tree + expect(mountingManagerLogsBeforeEndOfTask).toEqual([ + 'Update {type: "RootView", nativeID: (root)}', + ]); + + // Commit made from React - it should mount the final React tree + // NOTE: The RootView update should not be included here, fixed + // in a following diff + expect(root.takeMountingManagerLogs()).toEqual([ + 'Update {type: "RootView", nativeID: (root)}', + 'Update {type: "View", nativeID: "view"}', + ]); + }); +}); diff --git a/packages/react-native/src/private/renderer/consistency/__tests__/UIConsistency-itest.js b/packages/react-native/src/private/renderer/consistency/__tests__/UIConsistency-itest.js index 526d4873196..31a945eecde 100644 --- a/packages/react-native/src/private/renderer/consistency/__tests__/UIConsistency-itest.js +++ b/packages/react-native/src/private/renderer/consistency/__tests__/UIConsistency-itest.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @fantom_flags enableFabricCommitBranching:* * @flow strict-local * @format */ diff --git a/packages/react-native/src/private/renderer/mounting/__tests__/Mounting-itest.js b/packages/react-native/src/private/renderer/mounting/__tests__/Mounting-itest.js index 16e2474401b..faea08c6d4a 100644 --- a/packages/react-native/src/private/renderer/mounting/__tests__/Mounting-itest.js +++ b/packages/react-native/src/private/renderer/mounting/__tests__/Mounting-itest.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @fantom_flags enableFabricCommitBranching:* * @flow strict-local * @format */ diff --git a/packages/react-native/src/private/testing/fantom/specs/NativeFantomTestSpecificMethods.js b/packages/react-native/src/private/testing/fantom/specs/NativeFantomTestSpecificMethods.js index 6277b704cdc..f10f0a8fecb 100644 --- a/packages/react-native/src/private/testing/fantom/specs/NativeFantomTestSpecificMethods.js +++ b/packages/react-native/src/private/testing/fantom/specs/NativeFantomTestSpecificMethods.js @@ -9,6 +9,7 @@ */ import type {TurboModule} from '../../../../../Libraries/TurboModule/RCTExport'; +import type {Float, Int32} from '../../../../../Libraries/Types/CodegenTypes'; import * as TurboModuleRegistry from '../../../../../Libraries/TurboModule/TurboModuleRegistry'; @@ -24,6 +25,7 @@ import * as TurboModuleRegistry from '../../../../../Libraries/TurboModule/Turbo export interface Spec extends TurboModule { +registerForcedCloneCommitHook: () => void; +takeFunctionAndNoop: (fn: () => void) => void; + +setRootNodeSize: (surfaceId: Int32, width: Float, height: Float) => void; } export default (TurboModuleRegistry.getEnforcing( diff --git a/packages/react-native/src/private/webapis/dom/nodes/__tests__/ReactNativeElement-itest.js b/packages/react-native/src/private/webapis/dom/nodes/__tests__/ReactNativeElement-itest.js index 1f650b95a3c..196348fee7c 100644 --- a/packages/react-native/src/private/webapis/dom/nodes/__tests__/ReactNativeElement-itest.js +++ b/packages/react-native/src/private/webapis/dom/nodes/__tests__/ReactNativeElement-itest.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @fantom_flags enableFabricCommitBranching:* * @flow strict-local * @format */