Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 188 additions & 0 deletions packages/react-native/React/Tests/Text/RCTTextDynamicTypeTests.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/*
* 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.
*/

#import <React/RCTComponentViewRegistry.h>
#import <React/RCTFabricSurface.h>
#import <React/RCTMountingManager.h>
#import <React/RCTParagraphComponentView.h>
#import <React/RCTScheduler.h>
#import <React/RCTSurfacePresenter.h>
#import <React/RCTSurfaceView.h>
#import <React/RCTUtils.h>
#import <XCTest/XCTest.h>
#import <objc/runtime.h>
#import <react/renderer/components/text/ParagraphShadowNode.h>
#import <react/renderer/runtimescheduler/RuntimeScheduler.h>
#import <react/utils/ContextContainer.h>

using namespace facebook::react;

@interface RCTTextDynamicTypeTests : XCTestCase
@end

@implementation RCTTextDynamicTypeTests

- (void)testSimulatedContentSizeCategoryNotificationRelayoutsMountedTextWithoutRemounting
{
XCTAssertTrue([NSThread isMainThread]);
UIApplication *application = RCTSharedApplication();
XCTAssertNotNil(application);
if (!application) {
return;
}

Method categoryGetter = class_getInstanceMethod(application.class, @selector(preferredContentSizeCategory));
XCTAssertNotEqual(categoryGetter, nullptr);
if (!categoryGetter) {
return;
}

RuntimeExecutor runtimeExecutor = [](std::function<void(facebook::jsi::Runtime &)> &&) {};
auto runtimeScheduler = std::make_shared<RuntimeScheduler>(runtimeExecutor);
auto contextContainer = std::make_shared<ContextContainer>();
contextContainer->insert(RuntimeSchedulerKey, std::weak_ptr<RuntimeScheduler>(runtimeScheduler));
RCTSurfacePresenter *presenter = [[RCTSurfacePresenter alloc] initWithContextContainer:contextContainer
runtimeExecutor:runtimeExecutor
bridgelessBindingsExecutor:std::nullopt];
__block RCTFabricSurface *surface = nil;
__block UIContentSizeCategory category = UIContentSizeCategoryLarge;
// Simulate the application's external category input, not OS Settings delivery or any renderer result.
IMP simulatedCategoryGetter = imp_implementationWithBlock(^UIContentSizeCategory(id) {
return category;
});
IMP originalCategoryGetter = method_setImplementation(categoryGetter, simulatedCategoryGetter);

@try {
UITraitCollection *largeTraits = [UITraitCollection traitCollectionWithTraitsFromCollections:@[
UITraitCollection.currentTraitCollection,
[UITraitCollection traitCollectionWithPreferredContentSizeCategory:UIContentSizeCategoryLarge]
]];
[largeTraits performAsCurrentTraitCollection:^{
surface = [[RCTFabricSurface alloc] initWithSurfacePresenter:presenter moduleName:@"" initialProperties:@{}];
UIView *hostView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 240, 1000)];
surface.view.frame = hostView.bounds;
[hostView addSubview:surface.view];
[surface setSize:hostView.bounds.size];
[surface start];

auto surfaceId = surface.surfaceHandler.getSurfaceId();
auto uiManager = presenter.scheduler.uiManager;
auto paragraphTag = surfaceId + 1;
auto paragraph = uiManager->createNode(
paragraphTag,
"RCTText",
surfaceId,
RawProps(folly::dynamic::object("fontFamily", "Helvetica")("fontSize", 16)("allowFontScaling", true)),
nullptr);
auto rawText = uiManager->createNode(
surfaceId + 2,
"RCTRawText",
surfaceId,
RawProps(folly::dynamic::object("text", "Dynamic Type changes this paragraph without remounting.")),
nullptr);
uiManager->appendChild(paragraph, rawText);
auto rootChildren = std::make_shared<std::vector<std::shared_ptr<const ShadowNode>>>();
rootChildren->push_back(paragraph);
uiManager->completeSurface(surfaceId, rootChildren, {});

auto currentParagraph = [&] {
return std::static_pointer_cast<const ParagraphShadowNode>(
uiManager->findShadowNodeByTag_DEPRECATED(paragraphTag));
};
auto largeParagraph = currentParagraph();
auto registry = presenter.mountingManager.componentViewRegistry;
RCTParagraphComponentView *paragraphView =
(RCTParagraphComponentView *)[registry findComponentViewWithTag:paragraphTag];
XCTAssertNotEqual(largeParagraph.get(), nullptr);
XCTAssertTrue([paragraphView isKindOfClass:RCTParagraphComponentView.class]);
if (!largeParagraph || ![paragraphView isKindOfClass:RCTParagraphComponentView.class]) {
return;
}
auto largeState = largeParagraph->getState();
auto largeSize = largeParagraph->getStateData().layoutSize;
auto constraints = surface.surfaceHandler.getLayoutConstraints();
UIView *paragraphSuperview = paragraphView.superview;
UIFont *largeFont = [paragraphView.attributedText attribute:NSFontAttributeName atIndex:0 effectiveRange:nil];
XCTAssertEqualObjects(
paragraphView.attributedText.string, @"Dynamic Type changes this paragraph without remounting.");
XCTAssertEqualObjects(largeFont.fontName, @"Helvetica");
XCTAssertEqualWithAccuracy(largeFont.pointSize, 16, 0.001);
XCTAssertEqualWithAccuracy(surface.surfaceHandler.getLayoutContext().fontSizeMultiplier, 1, 0.0001);
XCTAssertGreaterThan(largeSize.height, 0);
XCTAssertEqualWithAccuracy(paragraphView.bounds.size.width, 240, 0.01);
XCTAssertEqualWithAccuracy(paragraphView.bounds.size.height, largeSize.height, 0.01);

UITraitCollection *accessibilityTraits = [UITraitCollection traitCollectionWithTraitsFromCollections:@[
largeTraits,
[UITraitCollection traitCollectionWithPreferredContentSizeCategory:UIContentSizeCategoryAccessibilityLarge]
]];
__block State::Shared accessibilityState;
[accessibilityTraits performAsCurrentTraitCollection:^{
category = UIContentSizeCategoryAccessibilityLarge;
[[NSNotificationCenter defaultCenter] postNotificationName:UIContentSizeCategoryDidChangeNotification
object:application
userInfo:@{UIContentSizeCategoryNewValueKey : category}];

auto accessibilityParagraph = currentParagraph();
XCTAssertNotEqual(accessibilityParagraph.get(), nullptr);
if (!accessibilityParagraph) {
return;
}
accessibilityState = accessibilityParagraph->getState();
const auto &data = accessibilityParagraph->getStateData();
UIFont *font = [paragraphView.attributedText attribute:NSFontAttributeName atIndex:0 effectiveRange:nil];
XCTAssertEqualWithAccuracy(surface.surfaceHandler.getLayoutContext().fontSizeMultiplier, 2.143, 0.0001);
XCTAssertTrue(surface.surfaceHandler.getLayoutConstraints() == constraints);
XCTAssertEqual(&accessibilityParagraph->getFamily(), &largeParagraph->getFamily());
XCTAssertEqual(accessibilityParagraph->getProps().get(), largeParagraph->getProps().get());
XCTAssertNotEqual(accessibilityState.get(), largeState.get());
XCTAssertFalse(data.attributedString.isContentEqual(largeParagraph->getStateData().attributedString));
XCTAssertEqualWithAccuracy(data.attributedString.getBaseTextAttributes().fontSizeMultiplier, 2.143, 0.0001);
XCTAssertEqualObjects(font.fontName, largeFont.fontName);
XCTAssertEqualWithAccuracy(font.pointSize, 16 * 2.143, 0.001);
XCTAssertGreaterThan(data.layoutSize.height, largeSize.height);
XCTAssertEqual([registry findComponentViewWithTag:paragraphTag], paragraphView);
XCTAssertEqual(paragraphView.superview, paragraphSuperview);
XCTAssertEqualWithAccuracy(paragraphView.bounds.size.width, 240, 0.01);
XCTAssertEqualWithAccuracy(paragraphView.bounds.size.height, data.layoutSize.height, 0.01);
}];

category = UIContentSizeCategoryLarge;
[[NSNotificationCenter defaultCenter] postNotificationName:UIContentSizeCategoryDidChangeNotification
object:application
userInfo:@{UIContentSizeCategoryNewValueKey : category}];
auto restoredParagraph = currentParagraph();
XCTAssertNotEqual(restoredParagraph.get(), nullptr);
if (!restoredParagraph) {
return;
}
const auto &restoredData = restoredParagraph->getStateData();
UIFont *restoredFont = [paragraphView.attributedText attribute:NSFontAttributeName atIndex:0 effectiveRange:nil];
XCTAssertEqualWithAccuracy(surface.surfaceHandler.getLayoutContext().fontSizeMultiplier, 1, 0.0001);
XCTAssertTrue(surface.surfaceHandler.getLayoutConstraints() == constraints);
XCTAssertEqual(&restoredParagraph->getFamily(), &largeParagraph->getFamily());
XCTAssertEqual(restoredParagraph->getProps().get(), largeParagraph->getProps().get());
XCTAssertNotEqual(restoredParagraph->getState().get(), accessibilityState.get());
XCTAssertTrue(restoredData.attributedString.isContentEqual(largeParagraph->getStateData().attributedString));
XCTAssertEqualObjects(restoredFont.fontName, largeFont.fontName);
XCTAssertEqualWithAccuracy(restoredFont.pointSize, largeFont.pointSize, 0.001);
XCTAssertEqualWithAccuracy(restoredData.layoutSize.width, largeSize.width, 0.01);
XCTAssertEqualWithAccuracy(restoredData.layoutSize.height, largeSize.height, 0.01);
XCTAssertEqual([registry findComponentViewWithTag:paragraphTag], paragraphView);
XCTAssertEqual(paragraphView.superview, paragraphSuperview);
XCTAssertEqualWithAccuracy(paragraphView.bounds.size.width, 240, 0.01);
XCTAssertEqualWithAccuracy(paragraphView.bounds.size.height, largeSize.height, 0.01);
}];
} @finally {
method_setImplementation(categoryGetter, originalCategoryGetter);
imp_removeBlock(simulatedCategoryGetter);
[surface stop];
[presenter suspend];
}
}

@end
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@
cmake_minimum_required(VERSION 3.13)
set(CMAKE_VERBOSE_MAKEFILE on)

include(${REACT_COMMON_DIR}/cmake-utils/internal/react-native-platform-selector.cmake)
include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake)

file(GLOB rrc_textinput_SRC CONFIGURE_DEPENDS *.cpp platform/android/react/renderer/components/androidtextinput/*.cpp)
react_native_android_selector(platform_SRC
platform/android/react/renderer/components/androidtextinput/*.cpp
"")
file(GLOB rrc_textinput_SRC CONFIGURE_DEPENDS *.cpp ${platform_SRC})
add_library(rrc_textinput OBJECT ${rrc_textinput_SRC})

target_include_directories(rrc_textinput PUBLIC . ${CMAKE_CURRENT_SOURCE_DIR}/platform/android/)
react_native_android_selector(platform_DIR
${CMAKE_CURRENT_SOURCE_DIR}/platform/android/
"")
target_include_directories(rrc_textinput PUBLIC . ${platform_DIR})

target_link_libraries(rrc_textinput
glog
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -556,15 +556,14 @@ void YogaLayoutableShadowNode::configureYogaTree(
YGConfigSetPointScaleFactor(&yogaConfig_, pointScaleFactor);

// A measurable node's measurement depends on `fontSizeMultiplier`, but unlike
// `pointScaleFactor` it is not part of the Yoga config, so a change does not
// invalidate Yoga's layout cache. Dirty the node when it changes to force
// re-measurement. We propagate up to the root so an unchanged, still-cached
// ancestor isn't skipped by `calculateLayoutInternal` before reaching us. An
// owner that is already dirty stops it; the child loop below covers that.
// `pointScaleFactor` it is not part of the Yoga config. Dirty the node to
// force re-measurement; the child loop below propagates to ancestors without
// crossing a `display: none` boundary.
if (getTraits().check(ShadowNodeTraits::Trait::MeasurableYogaNode) &&
!floatEquality(
getLayoutMetrics().fontSizeMultiplier, fontSizeMultiplier)) {
yogaNode_.markDirtyAndPropagate();
yogaNode_.setDirty(true);
yogaNode_.setLayoutComputedFlexBasis(yoga::FloatOptional{});
}

// TODO: `swapLeftAndRight` modified backing props and cannot be undone
Expand Down Expand Up @@ -611,6 +610,7 @@ void YogaLayoutableShadowNode::configureYogaTree(
if (updatedYogaNode.isDirty() && !yogaNode_.isDirty() &&
yogaNode_.style().display() != yoga::Display::None) {
yogaNode_.setDirty(true);
yogaNode_.setLayoutComputedFlexBasis(yoga::FloatOptional{});
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -968,6 +968,145 @@ TEST_F(FontScaleLayoutTest, fontScaleChangeLaysOutInputLikeNodeWithoutModal) {
expectLaidOutWithFontScale(*smallerRootShadowNode, 1);
}

TEST_F(FontScaleLayoutTest, fontScaleAndResizeInvalidatePercentageFlexBasis) {
auto rootShadowNode = std::shared_ptr<RootShadowNode>{};
auto element =
Element<RootShadowNode>()
.reference(rootShadowNode)
.tag(1)
.props([] {
auto props = std::make_shared<RootProps>();
props->layoutConstraints = {
.minimumSize = {.width = 100, .height = 100},
.maximumSize = {.width = 100, .height = 100}};
props->yogaStyle.setDimension(
yoga::Dimension::Width, yoga::StyleSizeLength::points(100));
props->yogaStyle.setDimension(
yoga::Dimension::Height, yoga::StyleSizeLength::points(100));
return props;
})
.children(
{Element<ViewShadowNode>()
.tag(2)
.props([] {
auto props = std::make_shared<ViewProps>();
props->yogaStyle.setDimension(
yoga::Dimension::Width,
yoga::StyleSizeLength::percent(100));
props->yogaStyle.setFlexDirection(
yoga::FlexDirection::Row);
props->yogaStyle.setAlignItems(yoga::Align::FlexStart);
return props;
})
.children(
{Element<FontScaledTextShadowNode>().tag(3).props([] {
auto props = std::make_shared<ViewProps>();
props->yogaStyle.setFlexBasis(
yoga::StyleSizeLength::percent(50));
props->yogaStyle.setFlexGrow(yoga::FloatOptional(0));
props->yogaStyle.setFlexShrink(yoga::FloatOptional(0));
props->yogaStyle.setDimension(
yoga::Dimension::Height,
yoga::StyleSizeLength::points(10));
return props;
})})});
builder_.build(element);
EXPECT_TRUE(rootShadowNode->layoutIfNeeded());

auto leafSize = [](const RootShadowNode& root) {
return static_cast<const LayoutableShadowNode&>(
*root.getChildren().at(0)->getChildren().at(0))
.getLayoutMetrics()
.frame.size;
};
EXPECT_EQ(leafSize(*rootShadowNode).width, 50);

auto constraints = rootShadowNode->getConcreteProps().layoutConstraints;
constraints.minimumSize.width = 200;
constraints.maximumSize.width = 200;
auto context = rootShadowNode->getConcreteProps().layoutContext;
context.fontSizeMultiplier = 1.5;
auto largerRoot = rootShadowNode->clone(parserContext_, constraints, context);
EXPECT_TRUE(largerRoot->layoutIfNeeded());
EXPECT_EQ(leafSize(*largerRoot).width, 100);
EXPECT_EQ(leafSize(*largerRoot).height, 10);

auto restoredRoot = largerRoot->clone(
parserContext_,
rootShadowNode->getConcreteProps().layoutConstraints,
rootShadowNode->getConcreteProps().layoutContext);
EXPECT_TRUE(restoredRoot->layoutIfNeeded());
EXPECT_EQ(leafSize(*restoredRoot).width, 50);
EXPECT_EQ(leafSize(*restoredRoot).height, 10);
}

TEST_F(FontScaleLayoutTest, fontScaleAndResizeInvalidateAncestorFlexBasis) {
auto rootShadowNode = std::shared_ptr<RootShadowNode>{};
auto element =
Element<RootShadowNode>()
.reference(rootShadowNode)
.tag(1)
.props([] {
auto props = std::make_shared<RootProps>();
props->layoutConstraints = {
.minimumSize = {.width = 100, .height = 100},
.maximumSize = {.width = 100, .height = 100}};
return props;
})
.children(
{Element<ViewShadowNode>()
.tag(2)
.props([] {
auto props = std::make_shared<ViewProps>();
props->yogaStyle.setDimension(
yoga::Dimension::Width,
yoga::StyleSizeLength::percent(100));
props->yogaStyle.setFlexDirection(
yoga::FlexDirection::Row);
return props;
})
.children({Element<ViewShadowNode>()
.tag(3)
.props([] {
auto props = std::make_shared<ViewProps>();
props->yogaStyle.setFlexBasis(
yoga::StyleSizeLength::percent(50));
props->yogaStyle.setFlexGrow(
yoga::FloatOptional(0));
props->yogaStyle.setFlexShrink(
yoga::FloatOptional(0));
return props;
})
.children({Element<FontScaledTextShadowNode>()
.tag(4)})})});
builder_.build(element);
EXPECT_TRUE(rootShadowNode->layoutIfNeeded());

auto wrapperWidth = [](const RootShadowNode& root) {
return static_cast<const LayoutableShadowNode&>(
*root.getChildren().at(0)->getChildren().at(0))
.getLayoutMetrics()
.frame.size.width;
};
EXPECT_EQ(wrapperWidth(*rootShadowNode), 50);

auto constraints = rootShadowNode->getConcreteProps().layoutConstraints;
constraints.minimumSize.width = 200;
constraints.maximumSize.width = 200;
auto context = rootShadowNode->getConcreteProps().layoutContext;
context.fontSizeMultiplier = 1.5;
auto largerRoot = rootShadowNode->clone(parserContext_, constraints, context);
EXPECT_TRUE(largerRoot->layoutIfNeeded());
EXPECT_EQ(wrapperWidth(*largerRoot), 100);

auto restoredRoot = largerRoot->clone(
parserContext_,
rootShadowNode->getConcreteProps().layoutConstraints,
rootShadowNode->getConcreteProps().layoutContext);
EXPECT_TRUE(restoredRoot->layoutIfNeeded());
EXPECT_EQ(wrapperWidth(*restoredRoot), 50);
}

TEST_F(FontScaleLayoutTest, fontScaleChangeSkipsHiddenSubtreeUntilShown) {
auto rootShadowNode = std::shared_ptr<RootShadowNode>{};
auto hiddenShadowNode = std::shared_ptr<ViewShadowNode>{};
Expand Down
Loading
Loading