Reland: Wire native CSS parsing for aspectRatio (#55882)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/55882

## Reland

`convertRawProp` for `yoga::Style` did not preserve `sourceValue.aspectRatio()` when `aspectRatio` was absent from the raw props diff. This caused `aspectRatio` to silently reset to undefined whenever any other prop was updated on a component that had `aspectRatio` set.

Fixed by adding an else-branch fallback to `sourceValue.aspectRatio()`:

```
{
    const auto *rawValue = rawProps.at("aspectRatio", nullptr, nullptr);
    if (rawValue != nullptr) {
      yogaStyle.setAspectRatio(rawValue->hasValue() ? convertAspectRatio(context, *rawValue) : yogaStyle.aspectRatio());
+   } else {
+     yogaStyle.setAspectRatio(sourceValue.aspectRatio());
    }
}
```

Added `clonedPropsPreserveAspectRatio` test in ViewTest.cpp to verify aspectRatio survives a prop clone with empty RawProps.

## Original

Gate `processAspectRatio` behind `enableNativeCSSParsing()`. When the flag is on, CSS ratio strings like `"16/9"` and number strings are parsed natively using the existing CSS ratio parser instead of being preprocessed in JS. The parsing is done in `fromRawValue(... FloatOptional &)` — string values are only sent for aspectRatio; other FloatOptional yoga props never receive strings from JS.

Changelog: [Internal]

Reviewed By: javache

Differential Revision: D95032494

fbshipit-source-id: f3c9724628d8ea7e570d1c91ddc38a6b59146070
This commit is contained in:
Nick Gerleman authored and meta-codesync[bot] committed 2026-03-05 00:40:46 -08:00
1 parent 2f6c744f01
commit a7ad793e32
7 files changed
+252 -31

No files matched your search

@@ -71,6 +71,10 @@ export const fontVariantAttribute: AnyAttributeType = nativeCSSParsing
? true
: {process: processFontVariant};
export const aspectRatioAttribute: AnyAttributeType = nativeCSSParsing
? true
: {process: processAspectRatio};
const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = {
/**
* Layout
@@ -78,7 +82,7 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = {
alignContent: true,
alignItems: true,
alignSelf: true,
aspectRatio: {process: processAspectRatio},
aspectRatio: aspectRatioAttribute,
borderBottomWidth: true,
borderEndWidth: true,
borderLeftWidth: true,
@@ -231,6 +231,101 @@ describe('<View>', () => {
});
});
describe('aspectRatio', () => {
it('is preserved when updating an unrelated prop', () => {
const root = Fantom.createRoot();
Fantom.runTask(() => {
root.render(
<View
style={{width: 100, aspectRatio: 2}}
nativeID="first"
collapsable={false}
/>,
);
});
// width=100, aspectRatio=2 → height = 100 / 2 = 50
expect(
root
.getRenderedOutput({
includeLayoutMetrics: true,
props: ['layoutMetrics-frame'],
})
.toJSX(),
).toEqual(
<rn-view layoutMetrics-frame="{x:0,y:0,width:100,height:50}" />,
);
// Update only nativeID, not aspectRatio
Fantom.runTask(() => {
root.render(
<View
style={{width: 100, aspectRatio: 2}}
nativeID="second"
collapsable={false}
/>,
);
});
// aspectRatio must still be preserved → same layout
expect(
root
.getRenderedOutput({
includeLayoutMetrics: true,
props: ['layoutMetrics-frame'],
})
.toJSX(),
).toEqual(
<rn-view layoutMetrics-frame="{x:0,y:0,width:100,height:50}" />,
);
});
it('can be changed to undefined after initially having a value', () => {
const root = Fantom.createRoot();
Fantom.runTask(() => {
root.render(
<View style={{width: 100, aspectRatio: 2}} collapsable={false} />,
);
});
// width=100, aspectRatio=2 → height = 100 / 2 = 50
expect(
root
.getRenderedOutput({
includeLayoutMetrics: true,
props: ['layoutMetrics-frame'],
})
.toJSX(),
).toEqual(
<rn-view layoutMetrics-frame="{x:0,y:0,width:100,height:50}" />,
);
// Update aspectRatio to undefined
Fantom.runTask(() => {
root.render(
<View
style={{width: 100, aspectRatio: undefined}}
collapsable={false}
/>,
);
});
// aspectRatio is now undefined → height collapses to 0
expect(
root
.getRenderedOutput({
includeLayoutMetrics: true,
props: ['layoutMetrics-frame'],
})
.toJSX(),
).toEqual(
<rn-view layoutMetrics-frame="{x:0,y:0,width:100,height:0}" />,
);
});
});
describe('background-image', () => {
it('it parses CSS and object syntax', () => {
const root = Fantom.createRoot();
@@ -147,35 +147,40 @@ void YogaStylableProps::setProp(
REBUILD_FIELD_SWITCH_CASE_YSP(flexBasis, setFlexBasis);
REBUILD_FIELD_SWITCH_CASE2(positionType, setPositionType, "position");
REBUILD_FIELD_YG_GUTTER(gap, setGap, "rowGap", "columnGap", "gap");
REBUILD_FIELD_SWITCH_CASE_YSP(aspectRatio, setAspectRatio);
REBUILD_FIELD_SWITCH_CASE_YSP(boxSizing, setBoxSizing);
REBUILD_FIELD_YG_DIMENSION(dimension, setDimension, "width", "height");
REBUILD_FIELD_YG_DIMENSION(
minDimension, setMinDimension, "minWidth", "minHeight");
REBUILD_FIELD_YG_DIMENSION(
maxDimension, setMaxDimension, "maxWidth", "maxHeight");
REBUILD_FIELD_YG_EDGES_POSITION();
REBUILD_FIELD_YG_EDGES(margin, setMargin, "margin", "");
REBUILD_FIELD_YG_EDGES(padding, setPadding, "padding", "");
REBUILD_FIELD_YG_EDGES(border, setBorder, "border", "Width");
case CONSTEXPR_RAW_PROPS_KEY_HASH("aspectRatio"): {
yogaStyle.setAspectRatio(
value.hasValue() ? convertAspectRatio(context, value)
: ygDefaults.aspectRatio());
return;
}
REBUILD_FIELD_SWITCH_CASE_YSP(boxSizing, setBoxSizing);
REBUILD_FIELD_YG_DIMENSION(dimension, setDimension, "width", "height");
REBUILD_FIELD_YG_DIMENSION(
minDimension, setMinDimension, "minWidth", "minHeight");
REBUILD_FIELD_YG_DIMENSION(
maxDimension, setMaxDimension, "maxWidth", "maxHeight");
REBUILD_FIELD_YG_EDGES_POSITION();
REBUILD_FIELD_YG_EDGES(margin, setMargin, "margin", "");
REBUILD_FIELD_YG_EDGES(padding, setPadding, "padding", "");
REBUILD_FIELD_YG_EDGES(border, setBorder, "border", "Width");
// Aliases
RAW_SET_PROP_SWITCH_CASE(insetBlockEnd, "insetBlockEnd");
RAW_SET_PROP_SWITCH_CASE(insetBlockStart, "insetBlockStart");
RAW_SET_PROP_SWITCH_CASE(insetInlineEnd, "insetInlineEnd");
RAW_SET_PROP_SWITCH_CASE(insetInlineStart, "insetInlineStart");
RAW_SET_PROP_SWITCH_CASE(marginInline, "marginInline");
RAW_SET_PROP_SWITCH_CASE(marginInlineStart, "marginInlineStart");
RAW_SET_PROP_SWITCH_CASE(marginInlineEnd, "marginInlineEnd");
RAW_SET_PROP_SWITCH_CASE(marginBlock, "marginBlock");
RAW_SET_PROP_SWITCH_CASE(marginBlockStart, "marginBlockStart");
RAW_SET_PROP_SWITCH_CASE(marginBlockEnd, "marginBlockEnd");
RAW_SET_PROP_SWITCH_CASE(paddingInline, "paddingInline");
RAW_SET_PROP_SWITCH_CASE(paddingInlineStart, "paddingInlineStart");
RAW_SET_PROP_SWITCH_CASE(paddingInlineEnd, "paddingInlineEnd");
RAW_SET_PROP_SWITCH_CASE(paddingBlock, "paddingBlock");
RAW_SET_PROP_SWITCH_CASE(paddingBlockStart, "paddingBlockStart");
RAW_SET_PROP_SWITCH_CASE(paddingBlockEnd, "paddingBlockEnd");
// Aliases
RAW_SET_PROP_SWITCH_CASE(insetBlockEnd, "insetBlockEnd");
RAW_SET_PROP_SWITCH_CASE(insetBlockStart, "insetBlockStart");
RAW_SET_PROP_SWITCH_CASE(insetInlineEnd, "insetInlineEnd");
RAW_SET_PROP_SWITCH_CASE(insetInlineStart, "insetInlineStart");
RAW_SET_PROP_SWITCH_CASE(marginInline, "marginInline");
RAW_SET_PROP_SWITCH_CASE(marginInlineStart, "marginInlineStart");
RAW_SET_PROP_SWITCH_CASE(marginInlineEnd, "marginInlineEnd");
RAW_SET_PROP_SWITCH_CASE(marginBlock, "marginBlock");
RAW_SET_PROP_SWITCH_CASE(marginBlockStart, "marginBlockStart");
RAW_SET_PROP_SWITCH_CASE(marginBlockEnd, "marginBlockEnd");
RAW_SET_PROP_SWITCH_CASE(paddingInline, "paddingInline");
RAW_SET_PROP_SWITCH_CASE(paddingInlineStart, "paddingInlineStart");
RAW_SET_PROP_SWITCH_CASE(paddingInlineEnd, "paddingInlineEnd");
RAW_SET_PROP_SWITCH_CASE(paddingBlock, "paddingBlock");
RAW_SET_PROP_SWITCH_CASE(paddingBlockStart, "paddingBlockStart");
RAW_SET_PROP_SWITCH_CASE(paddingBlockEnd, "paddingBlockEnd");
}
}
@@ -498,6 +498,23 @@ inline void fromRawValue(const PropsParserContext &context, const RawValue &valu
result = value.hasType<float>() ? yoga::FloatOptional((float)value) : yoga::FloatOptional();
}
inline yoga::FloatOptional convertAspectRatio(const PropsParserContext & /*context*/, const RawValue &value)
{
if (value.hasType<float>()) {
return yoga::FloatOptional((float)value);
}
if (ReactNativeFeatureFlags::enableNativeCSSParsing() && value.hasType<std::string>()) {
auto ratio = parseCSSProperty<CSSRatio>((std::string)value);
if (std::holds_alternative<CSSRatio>(ratio)) {
auto r = std::get<CSSRatio>(ratio);
if (!r.isDegenerate()) {
return yoga::FloatOptional(r.numerator / r.denominator);
}
}
}
return {};
}
inline std::optional<Float> toRadians(const RawValue &value)
{
if (value.hasType<Float>()) {
@@ -356,8 +356,14 @@ convertRawProp(const PropsParserContext &context, const RawProps &rawProps, cons
yoga::Dimension::Height,
convertRawProp(context, rawProps, "maxHeight", sourceValue.maxDimension(yoga::Dimension::Height), {}));
yogaStyle.setAspectRatio(
convertRawProp(context, rawProps, "aspectRatio", sourceValue.aspectRatio(), yogaStyle.aspectRatio()));
{
const auto *rawValue = rawProps.at("aspectRatio", nullptr, nullptr);
if (rawValue != nullptr) {
yogaStyle.setAspectRatio(rawValue->hasValue() ? convertAspectRatio(context, *rawValue) : yogaStyle.aspectRatio());
} else {
yogaStyle.setAspectRatio(sourceValue.aspectRatio());
}
}
yogaStyle.setBoxSizing(
convertRawProp(context, rawProps, "boxSizing", sourceValue.boxSizing(), yogaStyle.boxSizing()));
@@ -480,4 +480,64 @@ TEST(ConversionsTest, unprocessed_font_variant_string_invalid) {
EXPECT_EQ((int)result, (int)FontVariant::Default);
}
TEST(ConversionsTest, convert_aspect_ratio_float) {
RawValue value{folly::dynamic(1.5)};
auto result =
convertAspectRatio(PropsParserContext{-1, ContextContainer{}}, value);
EXPECT_FALSE(result.isUndefined());
EXPECT_EQ(result.unwrap(), 1.5f);
}
TEST(ConversionsTest, convert_aspect_ratio_ratio_string) {
// CSSRatio parses "16/9" as {numerator: 16, denominator: 9}
auto ratio = parseCSSProperty<CSSRatio>("16/9");
ASSERT_TRUE(std::holds_alternative<CSSRatio>(ratio));
auto r = std::get<CSSRatio>(ratio);
EXPECT_FALSE(r.isDegenerate());
EXPECT_NEAR(r.numerator / r.denominator, 16.0f / 9.0f, 0.001f);
}
TEST(ConversionsTest, convert_aspect_ratio_number_string) {
// CSSRatio parses "1.5" as {numerator: 1.5, denominator: 1.0}
auto ratio = parseCSSProperty<CSSRatio>("1.5");
ASSERT_TRUE(std::holds_alternative<CSSRatio>(ratio));
auto r = std::get<CSSRatio>(ratio);
EXPECT_FALSE(r.isDegenerate());
EXPECT_EQ(r.numerator / r.denominator, 1.5f);
}
TEST(ConversionsTest, convert_aspect_ratio_degenerate) {
auto ratio = parseCSSProperty<CSSRatio>("0/0");
ASSERT_TRUE(std::holds_alternative<CSSRatio>(ratio));
EXPECT_TRUE(std::get<CSSRatio>(ratio).isDegenerate());
}
TEST(ConversionsTest, float_optional_from_rawvalue_float) {
RawValue value{folly::dynamic(1.5)};
yoga::FloatOptional result;
fromRawValue(PropsParserContext{-1, ContextContainer{}}, value, result);
EXPECT_FALSE(result.isUndefined());
EXPECT_EQ(result.unwrap(), 1.5f);
}
TEST(ConversionsTest, float_optional_undefined_for_non_float) {
RawValue value{folly::dynamic(nullptr)};
yoga::FloatOptional result;
fromRawValue(PropsParserContext{-1, ContextContainer{}}, value, result);
EXPECT_TRUE(result.isUndefined());
}
TEST(ConversionsTest, float_optional_undefined_for_string) {
// fromRawValue for FloatOptional does not parse strings —
// that is handled by convertAspectRatio specifically.
RawValue value{folly::dynamic("16/9")};
yoga::FloatOptional result;
fromRawValue(PropsParserContext{-1, ContextContainer{}}, value, result);
EXPECT_TRUE(result.isUndefined());
}
} // namespace facebook::react
@@ -19,6 +19,7 @@
#include <react/renderer/element/Element.h>
#include <react/renderer/element/testUtils.h>
#include <yoga/numeric/FloatOptional.h>
namespace facebook::react {
@@ -229,4 +230,37 @@ TEST_F(YogaDirtyFlagTest, updatingStateForScrollViewMistNotDirtyYogaNode) {
static_cast<RootShadowNode&>(*newRootShadowNode).layoutIfNeeded());
}
TEST_F(YogaDirtyFlagTest, clonedPropsPreserveAspectRatio) {
ContextContainer contextContainer{};
PropsParserContext parserContext{-1, contextContainer};
/*
* Cloning props with empty RawProps must preserve aspectRatio set on the
* source props.
*/
auto newRootShadowNode = rootShadowNode_->cloneTree(
innerShadowNode_->getFamily(), [&](const ShadowNode& oldShadowNode) {
// First clone: set aspectRatio to 1.5
auto viewProps = std::make_shared<ViewShadowNodeProps>();
viewProps->yogaStyle.setAspectRatio(yoga::FloatOptional(1.5f));
auto nodeWithAspectRatio =
oldShadowNode.clone(ShadowNodeFragment{.props = viewProps});
// Second clone: clone props with empty RawProps (simulating a prop
// update that does not touch aspectRatio)
auto& componentDescriptor =
nodeWithAspectRatio->getComponentDescriptor();
auto clonedProps = componentDescriptor.cloneProps(
parserContext, nodeWithAspectRatio->getProps(), RawProps());
auto& clonedViewProps =
static_cast<const ViewShadowNodeProps&>(*clonedProps);
EXPECT_TRUE(clonedViewProps.yogaStyle.aspectRatio().isDefined());
EXPECT_EQ(clonedViewProps.yogaStyle.aspectRatio().unwrap(), 1.5f);
return nodeWithAspectRatio->clone(
ShadowNodeFragment{.props = clonedProps});
});
}
} // namespace facebook::react