first commit

This commit is contained in:
2026-03-10 16:18:05 +00:00
commit 11f9c069b5
31635 changed files with 3187747 additions and 0 deletions

View File

@@ -0,0 +1,80 @@
/*
* 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 "CullingContext.h"
#include <react/featureflags/ReactNativeFeatureFlags.h>
#include <react/renderer/components/scrollview/ScrollViewShadowNode.h>
#include <react/renderer/core/LayoutableShadowNode.h>
#include "ShadowViewNodePair.h"
namespace facebook::react {
bool CullingContext::shouldConsiderCulling() const {
return frame.size.width > 0 && frame.size.height > 0;
}
CullingContext CullingContext::adjustCullingContextIfNeeded(
const ShadowViewNodePair& pair) const {
auto cullingContext = *this;
if (ReactNativeFeatureFlags::enableViewCulling()) {
if (auto scrollViewShadowNode =
dynamic_cast<const ScrollViewShadowNode*>(pair.shadowNode)) {
if (scrollViewShadowNode->getConcreteProps().yogaStyle.overflow() !=
yoga::Overflow::Visible &&
!scrollViewShadowNode->getStateData().disableViewCulling) {
auto layoutMetrics = scrollViewShadowNode->getLayoutMetrics();
cullingContext.frame.origin =
-scrollViewShadowNode->getContentOriginOffset(
/* includeTransform */ true);
cullingContext.frame.size =
scrollViewShadowNode->getLayoutMetrics().frame.size;
// Enlarge the frame if an outset ratio is defined
auto outsetRatio = ReactNativeFeatureFlags::viewCullingOutsetRatio();
if (outsetRatio > 0) {
auto xOutset = static_cast<float>(
floor(cullingContext.frame.size.width * outsetRatio));
auto yOutset = static_cast<float>(
floor(cullingContext.frame.size.height * outsetRatio));
cullingContext.frame.origin.x -= xOutset;
cullingContext.frame.origin.y -= yOutset;
cullingContext.frame.size.width += 2.0f * xOutset;
cullingContext.frame.size.height += 2.0f * yOutset;
}
cullingContext.transform = Transform::Identity();
if (layoutMetrics.layoutDirection == LayoutDirection::RightToLeft) {
// In RTL, content offset is flipped horizontally.
// We need to flip the culling context frame to match.
// See:
// https://github.com/facebook/react-native/blob/c2f39cfdd87c32b9a59efe8a788b8a03f02b0ea0/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTScrollViewComponentView.mm#L579
auto stateData = scrollViewShadowNode->getStateData();
cullingContext.frame.origin.x =
stateData.contentBoundingRect.size.width -
layoutMetrics.frame.size.width - cullingContext.frame.origin.x;
}
} else {
cullingContext = {};
}
} else if (pair.shadowView.traits.check(
ShadowNodeTraits::Trait::RootNodeKind)) {
cullingContext = {};
} else {
cullingContext.frame.origin -= pair.shadowView.layoutMetrics.frame.origin;
if (auto layoutableShadowNode =
dynamic_cast<const LayoutableShadowNode*>(pair.shadowNode)) {
cullingContext.transform =
cullingContext.transform * layoutableShadowNode->getTransform();
}
}
}
return cullingContext;
}
} // namespace facebook::react

View File

@@ -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.
*/
#pragma once
#include <react/renderer/graphics/Rect.h>
#include <react/renderer/graphics/Transform.h>
namespace facebook::react {
struct ShadowViewNodePair;
struct CullingContext {
Rect frame;
Transform transform;
bool shouldConsiderCulling() const;
CullingContext adjustCullingContextIfNeeded(const ShadowViewNodePair &pair) const;
bool operator==(const CullingContext &rhs) const = default;
};
} // namespace facebook::react

View File

@@ -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.
*/
#pragma once
#include <react/renderer/core/ShadowNode.h>
#include <react/renderer/graphics/Point.h>
#include <react/renderer/mounting/ShadowView.h>
namespace facebook::react {
/*
* Describes pair of a `ShadowView` and a `ShadowNode`.
* This is not exposed to the mounting layer.
*/
struct ShadowViewNodePair final {
ShadowView shadowView{};
const ShadowNode *shadowNode;
/**
* The ShadowNode does not form a stacking context, and the native views
* corresponding to its children may be parented to an ancestor.
*/
bool flattened{false};
/**
* Whether this ShadowNode should create a corresponding native view.
*/
bool isConcreteView{true};
Point contextOrigin{0, 0};
size_t mountIndex{0};
/**
* This is nullptr unless `inOtherTree` is set to true.
* We rely on this only for marginal cases. TODO: could we
* rely on this more heavily to simplify the diffing algorithm
* overall?
*/
mutable const ShadowViewNodePair *otherTreePair{nullptr};
/*
* The stored pointer to `ShadowNode` represents an identity of the pair.
*/
bool operator==(const ShadowViewNodePair &rhs) const
{
return this->shadowNode == rhs.shadowNode;
}
bool operator!=(const ShadowViewNodePair &rhs) const
{
return !(*this == rhs);
}
bool inOtherTree() const
{
return this->otherTreePair != nullptr;
}
};
} // namespace facebook::react

View File

@@ -0,0 +1,147 @@
/*
* 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 <algorithm>
#include <utility>
/*
* Extremely simple and naive implementation of a map.
* The map is simple but it's optimized for particular constraints that we have
* here.
*
* A regular map implementation (e.g. `std::unordered_map`) has some basic
* performance guarantees like constant average insertion and lookup complexity.
* This is nice, but it's *average* complexity measured on a non-trivial amount
* of data. The regular map is a very complex data structure that using hashing,
* buckets, multiple comprising operations, multiple allocations and so on.
*
* In our particular case, we need a map for `int` to `void *` with a dozen
* values. In these conditions, nothing can beat a naive implementation using a
* stack-allocated vector. And this implementation is exactly this: no
* allocation, no hashing, no complex branching, no buckets, no iterators, no
* rehashing, no other guarantees. It's crazy limited, unsafe, and performant on
* a trivial amount of data.
*
* Besides that, we also need to optimize for insertion performance (the case
* where a bunch of views appears on the screen first time); in this
* implementation, this is as performant as vector `push_back`.
*/
template <typename KeyT, typename ValueT>
class TinyMap final {
public:
using Pair = std::pair<KeyT, ValueT>;
using Iterator = Pair *;
/**
* This must strictly only be called from outside of this class.
*/
inline Iterator begin()
{
// Force a clean so that iterating over this TinyMap doesn't iterate over
// erased elements. If all elements erased are at the front of the vector,
// then we don't need to clean.
cleanVector(erasedAtFront_ != numErased_);
Iterator it = begin_();
if (it != nullptr) {
return it + erasedAtFront_;
}
return nullptr;
}
inline Iterator end()
{
// `back()` asserts on the vector being non-empty
if (vector_.empty() || numErased_ == vector_.size()) {
return nullptr;
}
return &vector_.back() + 1;
}
inline Iterator find(KeyT key)
{
cleanVector();
react_native_assert(key != 0);
if (begin_() == nullptr) {
return end();
}
for (auto it = begin_() + erasedAtFront_; it != end(); it++) {
if (it->first == key) {
return it;
}
}
return end();
}
inline void insert(Pair pair)
{
react_native_assert(pair.first != 0);
vector_.push_back(pair);
}
inline void erase(Iterator iterator)
{
// Invalidate tag.
iterator->first = 0;
if (iterator == begin_() + erasedAtFront_) {
erasedAtFront_++;
}
numErased_++;
}
private:
/**
* Same as begin() but doesn't call cleanVector at the beginning.
*/
inline Iterator begin_()
{
// `front()` asserts on the vector being non-empty
if (vector_.empty() || vector_.size() == numErased_) {
return nullptr;
}
return &vector_.front();
}
/**
* Remove erased elements from internal vector.
* We only modify the vector if erased elements are at least half of the
* vector.
*/
inline void cleanVector(bool forceClean = false)
{
if ((numErased_ < (vector_.size() / 2) && !forceClean) || vector_.empty() || numErased_ == 0 ||
numErased_ == erasedAtFront_) {
return;
}
if (numErased_ == vector_.size()) {
vector_.clear();
} else {
vector_.erase(
std::remove_if(vector_.begin(), vector_.end(), [](const auto &item) { return item.first == 0; }),
vector_.end());
}
numErased_ = 0;
erasedAtFront_ = 0;
}
std::vector<Pair> vector_;
size_t numErased_{0};
size_t erasedAtFront_{0};
};

View File

@@ -0,0 +1,204 @@
/*
* 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 "sliceChildShadowNodeViewPairs.h"
#include <react/featureflags/ReactNativeFeatureFlags.h>
#include <react/renderer/core/LayoutableShadowNode.h>
#include "ShadowViewNodePair.h"
namespace facebook::react {
/*
* Sorting comparator for `reorderInPlaceIfNeeded`.
*/
static bool shouldFirstPairComesBeforeSecondOne(
const ShadowViewNodePair* lhs,
const ShadowViewNodePair* rhs) noexcept {
return lhs->shadowNode->getOrderIndex() < rhs->shadowNode->getOrderIndex();
}
/*
* Reorders pairs in-place based on `orderIndex` using a stable sort algorithm.
*/
static void reorderInPlaceIfNeeded(
std::vector<ShadowViewNodePair*>& pairs) noexcept {
if (pairs.size() < 2) {
return;
}
auto isReorderNeeded = false;
for (const auto& pair : pairs) {
if (pair->shadowNode->getOrderIndex() != 0) {
isReorderNeeded = true;
break;
}
}
if (!isReorderNeeded) {
return;
}
std::stable_sort(
pairs.begin(), pairs.end(), &shouldFirstPairComesBeforeSecondOne);
}
static void sliceChildShadowNodeViewPairsRecursively(
std::vector<ShadowViewNodePair*>& pairList,
size_t& startOfStaticIndex,
ViewNodePairScope& scope,
Point layoutOffset,
const ShadowNode& shadowNode,
const CullingContext& cullingContext) {
for (const auto& sharedChildShadowNode : shadowNode.getChildren()) {
auto& childShadowNode = *sharedChildShadowNode;
// T153547836: Disabled on Android because the mounting infrastructure
// is not fully ready yet.
if (
#ifdef ANDROID
ReactNativeFeatureFlags::useTraitHiddenOnAndroid() &&
#endif
childShadowNode.getTraits().check(ShadowNodeTraits::Trait::Hidden)) {
continue;
}
auto shadowView = ShadowView(childShadowNode);
if (ReactNativeFeatureFlags::enableViewCulling()) {
auto isViewCullable =
!shadowView.traits.check(
ShadowNodeTraits::Trait::Unstable_uncullableView) &&
!shadowView.traits.check(
ShadowNodeTraits::Trait::Unstable_uncullableTrace);
if (cullingContext.shouldConsiderCulling() && isViewCullable) {
auto overflowInsetFrame =
shadowView.layoutMetrics.getOverflowInsetFrame() *
cullingContext.transform;
if (auto layoutableShadowNode =
dynamic_cast<const LayoutableShadowNode*>(&childShadowNode)) {
overflowInsetFrame =
overflowInsetFrame * layoutableShadowNode->getTransform();
}
// Embedded Text components can have an empty layout, while these still
// need to be mounted to set the correct react tags on the text
// fragments. These should not be culled.
auto hasLayout = overflowInsetFrame.size.width > 0 ||
overflowInsetFrame.size.height > 0;
auto doesIntersect =
Rect::intersect(cullingContext.frame, overflowInsetFrame) != Rect{};
if (hasLayout && !doesIntersect) {
continue; // Culling.
}
}
}
auto origin = layoutOffset;
auto cullingContextCopy = cullingContext.adjustCullingContextIfNeeded(
{.shadowView = shadowView, .shadowNode = &childShadowNode});
if (shadowView.layoutMetrics != EmptyLayoutMetrics) {
origin += shadowView.layoutMetrics.frame.origin;
shadowView.layoutMetrics.frame.origin += layoutOffset;
}
// This might not be a FormsView, or a FormsStackingContext. We let the
// differ handle removal of flattened views from the Mounting layer and
// shuffling their children around.
bool childrenFormStackingContexts = shadowNode.getTraits().check(
ShadowNodeTraits::Trait::ChildrenFormStackingContext);
bool isConcreteView = (childShadowNode.getTraits().check(
ShadowNodeTraits::Trait::FormsView) ||
childrenFormStackingContexts) &&
!childShadowNode.getTraits().check(
ShadowNodeTraits::Trait::ForceFlattenView);
bool areChildrenFlattened =
(!childShadowNode.getTraits().check(
ShadowNodeTraits::Trait::FormsStackingContext) &&
!childrenFormStackingContexts) ||
childShadowNode.getTraits().check(
ShadowNodeTraits::Trait::ForceFlattenView);
Point storedOrigin = {};
if (areChildrenFlattened) {
storedOrigin = origin;
}
scope.push_back(
{shadowView,
&childShadowNode,
areChildrenFlattened,
isConcreteView,
storedOrigin});
if (shadowView.layoutMetrics.positionType == PositionType::Static) {
auto it = pairList.begin();
std::advance(it, startOfStaticIndex);
pairList.insert(it, &scope.back());
startOfStaticIndex++;
if (areChildrenFlattened) {
sliceChildShadowNodeViewPairsRecursively(
pairList,
startOfStaticIndex,
scope,
origin,
childShadowNode,
cullingContextCopy);
}
} else {
pairList.push_back(&scope.back());
if (areChildrenFlattened) {
size_t pairListSize = pairList.size();
sliceChildShadowNodeViewPairsRecursively(
pairList,
pairListSize,
scope,
origin,
childShadowNode,
cullingContextCopy);
}
}
}
}
std::vector<ShadowViewNodePair*> sliceChildShadowNodeViewPairs(
const ShadowViewNodePair& shadowNodePair,
ViewNodePairScope& scope,
bool allowFlattened,
Point layoutOffset,
const CullingContext& cullingContext) {
const auto& shadowNode = *shadowNodePair.shadowNode;
auto pairList = std::vector<ShadowViewNodePair*>{};
if (shadowNodePair.flattened && shadowNodePair.isConcreteView &&
!allowFlattened) {
return pairList;
}
size_t startOfStaticIndex = 0;
sliceChildShadowNodeViewPairsRecursively(
pairList,
startOfStaticIndex,
scope,
layoutOffset,
shadowNode,
cullingContext);
// Sorting pairs based on `orderIndex` if needed.
reorderInPlaceIfNeeded(pairList);
// Set list and mountIndex for each after reordering
size_t mountIndex = 0;
for (auto child : pairList) {
child->mountIndex =
(child->isConcreteView ? mountIndex++ : static_cast<unsigned long>(-1));
}
return pairList;
}
} // namespace facebook::react

View File

@@ -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
#include <deque>
#include "CullingContext.h"
namespace facebook::react {
struct ShadowViewNodePair;
/**
* During differ, we need to keep some `ShadowViewNodePair`s in memory.
* Some `ShadowViewNodePair`s are referenced from std::vectors returned
* by `sliceChildShadowNodeViewPairs`; some are referenced in TinyMaps
* for view (un)flattening especially; and it is not always clear which
* std::vectors will outlive which TinyMaps, and vice-versa, so it doesn't
* make sense for the std::vector or TinyMap to own any `ShadowViewNodePair`s.
*
* Thus, we introduce the concept of a scope.
*
* For the duration of some operation, we keep a ViewNodePairScope around, such
* that: (1) the ViewNodePairScope keeps each
* ShadowViewNodePair alive, (2) we have a stable pointer value that we can
* use to reference each ShadowViewNodePair (not guaranteed with std::vector,
* for example, which may have to resize and move values around).
*
* As long as we only manipulate the data-structure with push_back, std::deque
* both (1) ensures that pointers into the data-structure are never invalidated,
* and (2) tries to efficiently allocate storage such that as many objects as
* possible are close in memory, but does not guarantee adjacency.
*/
using ViewNodePairScope = std::deque<ShadowViewNodePair>;
/**
* Generates a list of `ShadowViewNodePair`s that represents a layer of a
* flattened view hierarchy. The V2 version preserves nodes even if they do
* not form views and their children are flattened.
*/
std::vector<ShadowViewNodePair *> sliceChildShadowNodeViewPairs(
const ShadowViewNodePair &shadowNodePair,
ViewNodePairScope &viewNodePairScope,
bool allowFlattened,
Point layoutOffset,
const CullingContext &cullingContext);
} // namespace facebook::react