Release Yoga ownership of children an unowned node shares with its clone

Summary:
**The Bug**

Showing a subtree hidden with `<Activity mode="hidden">` again can abort debug builds with `Attempt to mutate a sealed object`. Release builds have no assertion, so the same layout pass silently changes shadow nodes that the committed tree still uses.

**The Cause**

React keeps the instance of a hidden host component, commits a `display: none` clone of it that shares its children, and appends the instance (or a clone of it) again when the subtree is shown. Since react/yoga#2055, zeroing out a `display: none` subtree no longer clones children that are already zeroed out, so the committed tree can share children that the kept instance owns. The instance itself is unowned, so appending it adopts it in place, and its layout treats the shared children as its own.

**The Fix**

Cloning an unowned `YogaLayoutableShadowNode` points the owner of the children it owns at the detached-owner sentinel, through `updateYogaChildrenOwnersIfNeeded`, which now takes the Yoga node to update. Whichever node lays those children out next (the kept instance or any clone of it) clones them first through the Yoga clone callback.

The kept instance's stale layout cache is already handled by comparing each new child's layout results in `updateYogaChildren`. react/yoga#2055's optimization stays in place.

Changelog:
[General][Fixed] - Fix showing a subtree hidden with `<Activity>` laying out shadow nodes in place that the committed tree still uses, which crashed debug builds

Reviewed By: lenaic

Differential Revision: D132556429

Pull Request resolved: https://github.com/react/react-native/pull/60082
This commit is contained in:
Pieter De Baets authored and GitHub committed 2026-11-17 17:19:39 +00:00
1 parent 6a695d86c0
commit 600b2b3136
4 files changed
+270 -5

No files matched your search

@@ -123,11 +123,20 @@ YogaLayoutableShadowNode::YogaLayoutableShadowNode(
&static_cast<const YogaLayoutableShadowNode&>(sourceShadowNode)
.yogaConfig_;
// An unowned source can be appended and laid out again after this clone is
// committed (React does this when it shows a hidden subtree again), so it
// must not keep owning the children it now shares with this clone.
auto& sourceYogaNode =
static_cast<const YogaLayoutableShadowNode&>(sourceShadowNode).yogaNode_;
if (YGNodeGetOwner(&sourceYogaNode) == nullptr) {
updateYogaChildrenOwnersIfNeeded(sourceYogaNode);
}
YGNodeSetContext(&yogaNode_, this);
yogaNode_.setOwner(nullptr);
YGNodeSetConfig(
&yogaNode_, &initializeYogaConfig(yogaConfig_, previousConfig));
updateYogaChildrenOwnersIfNeeded();
updateYogaChildrenOwnersIfNeeded(yogaNode_);
// We do not need to reconfigure this subtree before the next layout pass if
// the previous node with the same props and children has already been
@@ -332,7 +341,8 @@ bool YogaLayoutableShadowNode::shouldNewRevisionDirtyMeasurement(
//
// No-op in the common case: right after a clone, children's owner
// pointers still reference the source node, not us.
void YogaLayoutableShadowNode::updateYogaChildrenOwnersIfNeeded() {
/*static*/ void YogaLayoutableShadowNode::updateYogaChildrenOwnersIfNeeded(
yoga::Node& yogaNode) {
// Magic constant intentionally recognisable in debuggers when the address
// pops up. `reinterpret_cast` is not constexpr, so this is a runtime-
// initialised function-local static.
@@ -340,8 +350,8 @@ void YogaLayoutableShadowNode::updateYogaChildrenOwnersIfNeeded() {
static auto* const kDetachedYogaNodeOwnerSentinel =
reinterpret_cast<yoga::Node*>(0xBADC0FFEE0DDF000ULL);
// NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
for (auto& childYogaNode : yogaNode_.getChildren()) {
if (YGNodeGetOwner(childYogaNode) == &yogaNode_) {
for (auto& childYogaNode : yogaNode.getChildren()) {
if (YGNodeGetOwner(childYogaNode) == &yogaNode) {
childYogaNode->setOwner(kDetachedYogaNodeOwnerSentinel);
}
}
@@ -110,7 +110,11 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode {
mutable yoga::Node yogaNode_;
private:
void updateYogaChildrenOwnersIfNeeded();
/*
* Points the owner of every child that `yogaNode` owns at a sentinel, so
* that whichever node lays the child out next clones it first.
*/
static void updateYogaChildrenOwnersIfNeeded(yoga::Node &yogaNode);
/*
* Return true if child's yogaNode's owner is this->yogaNode_. Otherwise
@@ -0,0 +1,190 @@
/*
* 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 <memory>
#include <vector>
#include <gtest/gtest.h>
#include <react/renderer/components/root/RootComponentDescriptor.h>
#include <react/renderer/components/view/ViewComponentDescriptor.h>
#include <react/renderer/element/ComponentBuilder.h>
#include <react/renderer/element/Element.h>
#include <react/renderer/element/testUtils.h>
namespace facebook::react {
namespace {
std::shared_ptr<const ViewProps> sizedProps(float width, float height) {
auto props = std::make_shared<ViewProps>();
props->yogaStyle.setDimension(
yoga::Dimension::Width, yoga::StyleSizeLength::points(width));
props->yogaStyle.setDimension(
yoga::Dimension::Height, yoga::StyleSizeLength::points(height));
return props;
}
std::shared_ptr<const ViewProps> displayNoneProps() {
auto props = std::make_shared<ViewProps>();
props->yogaStyle.setDisplay(yoga::Display::None);
return props;
}
std::shared_ptr<ShadowNode> cloneWithChild(
const ShadowNode& shadowNode,
const std::shared_ptr<const ShadowNode>& child) {
auto children =
std::make_shared<const std::vector<std::shared_ptr<const ShadowNode>>>(
std::vector<std::shared_ptr<const ShadowNode>>{child});
return shadowNode.clone(
ShadowNodeFragment{
.props = ShadowNodeFragment::propsPlaceholder(),
.children = children});
}
std::shared_ptr<ShadowNode> cloneHidden(const ShadowNode& shadowNode) {
return shadowNode.clone(ShadowNodeFragment{.props = displayNoneProps()});
}
std::shared_ptr<RootShadowNode> commit(
const std::shared_ptr<ShadowNode>& root) {
auto rootShadowNode = std::static_pointer_cast<RootShadowNode>(root);
rootShadowNode->layoutIfNeeded();
rootShadowNode->sealRecursive();
return rootShadowNode;
}
Size frameSize(const std::shared_ptr<const ShadowNode>& shadowNode) {
return static_cast<const LayoutableShadowNode&>(*shadowNode)
.getLayoutMetrics()
.frame.size;
}
std::vector<LayoutMetrics> subtreeLayoutMetrics(const ShadowNode& shadowNode) {
std::vector<LayoutMetrics> metrics{
static_cast<const LayoutableShadowNode&>(shadowNode).getLayoutMetrics()};
for (const auto& child : shadowNode.getChildren()) {
auto childMetrics = subtreeLayoutMetrics(*child);
metrics.insert(metrics.end(), childMetrics.begin(), childMetrics.end());
}
return metrics;
}
} // namespace
// React keeps the instance of a hidden subtree, commits a `display: none`
// clone of it that shares its children, and appends the instance (or a clone
// of it) again when the subtree is shown. The parameter is the size of the
// instance's child: a zero-sized child keeps its frame when it is zeroed out.
class RevealHiddenInstanceTest : public ::testing::TestWithParam<float> {
protected:
RevealHiddenInstanceTest() {
std::shared_ptr<RootShadowNode> rootShadowNode;
std::shared_ptr<ViewShadowNode> instance;
// clang-format off
auto element =
Element<RootShadowNode>()
.reference(rootShadowNode)
.tag(1)
.props([] {
auto props = std::make_shared<RootProps>();
props->layoutConstraints = LayoutConstraints{
.minimumSize = {.width = 0, .height = 0},
.maximumSize = {.width = 200, .height = 200}};
return props;
})
.children({
Element<ViewShadowNode>()
.reference(instance)
.tag(2)
.props([] { return sizedProps(100, 100); })
.children({
Element<ViewShadowNode>()
.tag(3)
.props([size = GetParam()] { return sizedProps(size, size); })
.children({
Element<ViewShadowNode>()
.tag(4)
.props([] { return sizedProps(10, 10); })
})
})
});
// clang-format on
builder_.build(element);
commit(rootShadowNode);
auto hiddenRoot =
commit(cloneWithChild(*rootShadowNode, cloneHidden(*instance)));
// An update while hidden starts from the child as laid out in the hidden
// tree, so the new instance owns a child that is already zeroed out.
const auto& zeroedOutChild =
hiddenRoot->getChildren().front()->getChildren().front();
hiddenChild_ = zeroedOutChild->clone(ShadowNodeFragment{});
instance_ = cloneWithChild(*instance, hiddenChild_);
hiddenRoot_ = commit(cloneWithChild(*hiddenRoot, cloneHidden(*instance_)));
}
void expectShownWithoutChangingHiddenTree(
const std::shared_ptr<const ShadowNode>& shownInstance) {
ASSERT_EQ(
hiddenRoot_->getChildren().front()->getChildren().front(),
hiddenChild_);
const auto hiddenTreeLayoutMetrics = subtreeLayoutMetrics(*hiddenRoot_);
auto shownRoot = std::static_pointer_cast<RootShadowNode>(
cloneWithChild(*hiddenRoot_, shownInstance));
shownRoot->layoutIfNeeded();
const auto& instance = shownRoot->getChildren().front();
const auto& child = instance->getChildren().front();
EXPECT_NE(child, hiddenChild_);
const std::vector<Size> expectedSizes{
{.width = 100, .height = 100},
{.width = GetParam(), .height = GetParam()},
{.width = 10, .height = 10}};
EXPECT_EQ(
(std::vector<Size>{
frameSize(instance),
frameSize(child),
frameSize(child->getChildren().front())}),
expectedSizes);
EXPECT_EQ(subtreeLayoutMetrics(*hiddenRoot_), hiddenTreeLayoutMetrics);
}
ComponentBuilder builder_{simpleComponentBuilder()};
std::shared_ptr<RootShadowNode> hiddenRoot_;
std::shared_ptr<const ShadowNode> instance_;
std::shared_ptr<const ShadowNode> hiddenChild_;
};
TEST_P(RevealHiddenInstanceTest, showingInstance) {
expectShownWithoutChangingHiddenTree(instance_);
}
TEST_P(RevealHiddenInstanceTest, showingCloneOfInstance) {
expectShownWithoutChangingHiddenTree(instance_->clone(ShadowNodeFragment{}));
}
TEST_P(RevealHiddenInstanceTest, showingCloneOfInstanceWithNewNonLayoutProp) {
auto props = std::make_shared<ViewProps>(
static_cast<const ViewProps&>(*instance_->getProps()));
props->backgroundColor = blackColor();
expectShownWithoutChangingHiddenTree(
instance_->clone(ShadowNodeFragment{.props = props}));
}
INSTANTIATE_TEST_SUITE_P(
ChildSizes,
RevealHiddenInstanceTest,
::testing::Values(50.0f, 0.0f));
} // namespace facebook::react
@@ -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.
*
* @flow strict-local
* @format
*/
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
import type {HostInstance} from 'react-native';
import * as Fantom from '@react-native/fantom';
import nullthrows from 'nullthrows';
import * as React from 'react';
import {Activity, createRef} from 'react';
import {View} from 'react-native';
describe('<Activity>', () => {
it('lays out a subtree shown again after it was updated while hidden', () => {
const root = Fantom.createRoot();
const childRef = createRef<HostInstance>();
const grandchildRef = createRef<HostInstance>();
const siblingRef = createRef<HostInstance>();
function render(mode: 'visible' | 'hidden', siblingWidth: number) {
Fantom.runTask(() => {
root.render(
<Activity mode={mode}>
<View style={{width: 100, height: 100}}>
<View ref={childRef} style={{width: 50, height: 50}}>
<View ref={grandchildRef} style={{width: 10, height: 10}} />
</View>
<View
ref={siblingRef}
style={{width: siblingWidth, height: 10}}
/>
</View>
</Activity>,
);
});
}
render('visible', 20);
render('hidden', 20);
// Updating the sibling while hidden appends the unchanged child as it was
// laid out (zeroed out) in the hidden tree.
render('hidden', 30);
render('visible', 30);
const sizeOf = (ref: {current: HostInstance | null}) => {
const rect = nullthrows(ref.current).getBoundingClientRect();
return [rect.width, rect.height];
};
expect(sizeOf(childRef)).toEqual([50, 50]);
expect(sizeOf(grandchildRef)).toEqual([10, 10]);
expect(sizeOf(siblingRef)).toEqual([30, 10]);
});
});