diff --git a/packages/react-native/React/Tests/Text/RCTTextDynamicTypeTests.mm b/packages/react-native/React/Tests/Text/RCTTextDynamicTypeTests.mm new file mode 100644 index 000000000000..8b09a6523076 --- /dev/null +++ b/packages/react-native/React/Tests/Text/RCTTextDynamicTypeTests.mm @@ -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 +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import + +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 &&) {}; + auto runtimeScheduler = std::make_shared(runtimeExecutor); + auto contextContainer = std::make_shared(); + contextContainer->insert(RuntimeSchedulerKey, std::weak_ptr(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>>(); + rootChildren->push_back(paragraph); + uiManager->completeSurface(surfaceId, rootChildren, {}); + + auto currentParagraph = [&] { + return std::static_pointer_cast( + 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 diff --git a/packages/react-native/ReactCommon/react/renderer/components/textinput/CMakeLists.txt b/packages/react-native/ReactCommon/react/renderer/components/textinput/CMakeLists.txt index 13cc489fb6e5..8e52edebac96 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/textinput/CMakeLists.txt +++ b/packages/react-native/ReactCommon/react/renderer/components/textinput/CMakeLists.txt @@ -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 diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp index 825334daf3d5..456baaf1f4e0 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp @@ -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 @@ -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{}); } } } diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewTest.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewTest.cpp index 1e0a06b31da1..584f62ec2435 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/tests/ViewTest.cpp @@ -968,6 +968,145 @@ TEST_F(FontScaleLayoutTest, fontScaleChangeLaysOutInputLikeNodeWithoutModal) { expectLaidOutWithFontScale(*smallerRootShadowNode, 1); } +TEST_F(FontScaleLayoutTest, fontScaleAndResizeInvalidatePercentageFlexBasis) { + auto rootShadowNode = std::shared_ptr{}; + auto element = + Element() + .reference(rootShadowNode) + .tag(1) + .props([] { + auto props = std::make_shared(); + 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() + .tag(2) + .props([] { + auto props = std::make_shared(); + 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().tag(3).props([] { + auto props = std::make_shared(); + 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( + *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{}; + auto element = + Element() + .reference(rootShadowNode) + .tag(1) + .props([] { + auto props = std::make_shared(); + props->layoutConstraints = { + .minimumSize = {.width = 100, .height = 100}, + .maximumSize = {.width = 100, .height = 100}}; + return props; + }) + .children( + {Element() + .tag(2) + .props([] { + auto props = std::make_shared(); + props->yogaStyle.setDimension( + yoga::Dimension::Width, + yoga::StyleSizeLength::percent(100)); + props->yogaStyle.setFlexDirection( + yoga::FlexDirection::Row); + return props; + }) + .children({Element() + .tag(3) + .props([] { + auto props = std::make_shared(); + props->yogaStyle.setFlexBasis( + yoga::StyleSizeLength::percent(50)); + props->yogaStyle.setFlexGrow( + yoga::FloatOptional(0)); + props->yogaStyle.setFlexShrink( + yoga::FloatOptional(0)); + return props; + }) + .children({Element() + .tag(4)})})}); + builder_.build(element); + EXPECT_TRUE(rootShadowNode->layoutIfNeeded()); + + auto wrapperWidth = [](const RootShadowNode& root) { + return static_cast( + *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{}; auto hiddenShadowNode = std::shared_ptr{}; diff --git a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js index 5b0807484325..64c0af4cfd0d 100644 --- a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js +++ b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js @@ -83,13 +83,16 @@ interface Spec extends TurboModule { viewportOffsetX?: number, viewportOffsetY?: number, ) => RootTag; - stopSurface: (surfaceId: RootTag) => void; updateSurfaceConstraints: ( surfaceId: RootTag, viewportWidth: number, viewportHeight: number, devicePixelRatio: number, + fontScale?: number, + viewportOffsetX?: number, + viewportOffsetY?: number, ) => void; + stopSurface: (surfaceId: RootTag) => void; enqueueNativeEvent: ( shadowNode: unknown /* ShadowNode */, type: string, diff --git a/private/react-native-fantom/__docs__/README.md b/private/react-native-fantom/__docs__/README.md index 40c4b6e6dbe4..2ad873a4350a 100644 --- a/private/react-native-fantom/__docs__/README.md +++ b/private/react-native-fantom/__docs__/README.md @@ -109,9 +109,18 @@ describe('My feature', () => { Creating a root sets global `Dimensions` for both `window` and `screen` from its `viewportWidth`, `viewportHeight`, `devicePixelRatio`, and optional `fontScale` (default `1`). `useWindowDimensions()` and `PixelRatio` report the new root's -values. If another root is still alive and the new metrics differ from the -current global dimensions, Fantom applies the new values and emits a warning. -Call `root.destroy()` when a root is no longer needed. +values. + +`root.updateSurfaceConstraints(config)` updates any viewport, pixel ratio, font +scale or viewport-offset fields supplied in `config`, preserving the others, and +runs the pending JavaScript work. To batch native changes without running +JavaScript, call `root.enqueueUpdateSurfaceConstraints(config)` within +`Fantom.runOnUIThread()`, then call `Fantom.runWorkLoop()` when ready. Existing +roots are updated without being registered again. + +If another root is still alive and the new metrics differ from the current +global dimensions, Fantom applies the new values and emits a warning. Call +`root.destroy()` when a root is no longer needed. `root.updateSurfaceConstraints(width, height)` changes native root constraints without rendering React or flushing pending work. Use it to test root and diff --git a/private/react-native-fantom/src/__tests__/Fantom-itest.js b/private/react-native-fantom/src/__tests__/Fantom-itest.js index 8f435e2356b8..7962f1bf4189 100644 --- a/private/react-native-fantom/src/__tests__/Fantom-itest.js +++ b/private/react-native-fantom/src/__tests__/Fantom-itest.js @@ -10,8 +10,8 @@ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; -import type {Root} from '@react-native/fantom'; -import type {HostInstance} from 'react-native'; +import type {Root, RootConfig} from '@react-native/fantom'; +import type {HostInstance, TextInputInstance} from 'react-native'; import NativeFantom from '../../../../packages/react-native/src/private/testing/fantom/specs/NativeFantom'; import * as Fantom from '@react-native/fantom'; @@ -51,6 +51,156 @@ function getActualViewportDimensions(root: Root): { describe('Fantom', () => { describe('root.updateSurfaceConstraints', () => { + describe('runtime font-scale changes', () => { + const cases = [ + { + name: 'default font scaling', + allowFontScaling: undefined, + maxFontSizeMultiplier: undefined, + expectedMultiplier: 2, + expectedTextInputMultiplier: 2, + }, + { + name: 'disabled font scaling', + allowFontScaling: false, + maxFontSizeMultiplier: undefined, + expectedMultiplier: 1, + expectedTextInputMultiplier: 1, + }, + { + name: 'capped font scaling', + allowFontScaling: undefined, + maxFontSizeMultiplier: 1.5, + expectedMultiplier: 1.5, + expectedTextInputMultiplier: 1.5, + }, + ]; + + for (const componentName of ['Text', 'TextInput']) { + for (const { + name, + allowFontScaling, + maxFontSizeMultiplier, + expectedMultiplier, + expectedTextInputMultiplier, + } of cases) { + it(`handles font-scale changes for mounted ${componentName} with ${name}`, () => { + const rootConfig: RootConfig = { + viewportWidth: 400, + viewportHeight: 600, + devicePixelRatio: 2, + fontScale: 1, + viewportOffsetX: 10, + viewportOffsetY: 20, + }; + const parentRef = createRef(); + const textRef = createRef(); + const inputRef = createRef(); + const content = ( + + {componentName === 'Text' ? ( + + text + + ) : ( + + )} + + ); + const expectedFontScale = + componentName === 'Text' + ? expectedMultiplier + : expectedTextInputMultiplier; + + // Mount and destroy the reference before creating the subject so global + // Dimensions changes cannot rerender it and invalidate its cached layout. + const referenceRoot = Fantom.createRoot({ + ...rootConfig, + fontScale: expectedFontScale, + }); + let expectedBounds; + try { + Fantom.runTask(() => referenceRoot.render(content)); + expectedBounds = nullthrows( + componentName === 'Text' ? textRef.current : inputRef.current, + ).getBoundingClientRect(); + } finally { + Fantom.runTask(() => referenceRoot.render(<>)); + referenceRoot.destroy(); + } + + const root = Fantom.createRoot(rootConfig); + try { + Fantom.runTask(() => root.render(content)); + + const parent = nullthrows(parentRef.current); + const text = textRef.current; + const input = inputRef.current; + const element = nullthrows( + componentName === 'Text' ? text : input, + ); + const parentBounds = parent.getBoundingClientRect(); + const initialBounds = element.getBoundingClientRect(); + expect(initialBounds.width).toBeGreaterThan(0); + expect(initialBounds.height).toBeGreaterThan(0); + if (expectedFontScale > 1) { + expect(expectedBounds.width).toBeGreaterThan( + initialBounds.width, + ); + expect(expectedBounds.height).toBeGreaterThan( + initialBounds.height, + ); + } + root.takeMountingManagerLogs(); + + root.updateSurfaceConstraints({fontScale: 2}); + + expect(parentRef.current).toBe(parent); + expect(parent.getBoundingClientRect()).toEqual(parentBounds); + expect(textRef.current).toBe(text); + expect(inputRef.current).toBe(input); + const scaledBounds = element.getBoundingClientRect(); + expect(scaledBounds.width).toBeCloseTo(expectedBounds.width); + expect(scaledBounds.height).toBeCloseTo(expectedBounds.height); + expect( + root + .takeMountingManagerLogs() + .filter(log => /^(Create|Delete|Insert|Remove) /.test(log)), + ).toEqual([]); + + root.updateSurfaceConstraints({fontScale: 1}); + + expect(parentRef.current).toBe(parent); + expect(parent.getBoundingClientRect()).toEqual(parentBounds); + expect(textRef.current).toBe(text); + expect(inputRef.current).toBe(input); + expect(element.getBoundingClientRect()).toEqual(initialBounds); + expect( + root + .takeMountingManagerLogs() + .filter(log => /^(Create|Delete|Insert|Remove) /.test(log)), + ).toEqual([]); + } finally { + Fantom.runTask(() => root.render(<>)); + root.destroy(); + } + }); + } + } + }); + it('resizes the root and percentage-sized descendants without another React render', () => { const root = Fantom.createRoot({viewportWidth: 100, viewportHeight: 80}); const nodeRef = createRef(); diff --git a/private/react-native-fantom/src/__tests__/FantomDimensions-itest.js b/private/react-native-fantom/src/__tests__/FantomDimensions-itest.js index edb818f9aac6..63739d81e622 100644 --- a/private/react-native-fantom/src/__tests__/FantomDimensions-itest.js +++ b/private/react-native-fantom/src/__tests__/FantomDimensions-itest.js @@ -13,9 +13,12 @@ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; import type {Root, RootConfig} from '@react-native/fantom'; +import type {HostInstance} from 'react-native'; import * as Fantom from '@react-native/fantom'; +import nullthrows from 'nullthrows'; import * as React from 'react'; +import {createRef} from 'react'; import {Dimensions, PixelRatio, View, useWindowDimensions} from 'react-native'; let roots: Array; @@ -175,6 +178,241 @@ it('restores the latest surviving root and then defaults when all roots are dest expect(PixelRatio.getFontScale()).toBe(1); }); +it('keeps numeric resizing separate from dimension updates and JavaScript work', () => { + const root = createRoot({viewportWidth: 120, viewportHeight: 140}); + const viewRef = createRef(); + Fantom.runTask(() => { + root.render(); + }); + const view = nullthrows(viewRef.current); + const previousDimensions = Dimensions.get('window'); + const task = jest.fn(); + Fantom.scheduleTask(task); + + Fantom.runOnUIThread(() => root.updateSurfaceConstraints(200, 240)); + + expect(view.getBoundingClientRect().width).toBe(200); + expect(view.getBoundingClientRect().height).toBe(240); + expect(viewRef.current).toBe(view); + expect(Dimensions.get('window')).toBe(previousDimensions); + expect(task).not.toHaveBeenCalled(); + + Fantom.runWorkLoop(); + expect(task).toHaveBeenCalledTimes(1); + expect(Dimensions.get('window')).toBe(previousDimensions); +}); + +it('updates font scale and notifies mounted components without changing other metrics', () => { + const root = createRoot({ + viewportWidth: 640, + viewportHeight: 480, + devicePixelRatio: 2, + viewportOffsetX: 10, + viewportOffsetY: 20, + }); + Fantom.runTask(() => root.render()); + + const previousDimensions = Dimensions.get('window'); + + root.updateSurfaceConstraints({fontScale: 1.5}); + + expect(root.getRenderedOutput({props: ['testID']}).toJSX()).toEqual( + , + ); + for (const dimension of ['window', 'screen']) { + expect(Dimensions.get(dimension)).toEqual({ + width: 640, + height: 480, + scale: 2, + fontScale: 1.5, + }); + } + expect(previousDimensions.fontScale).toBe(1); + expect(PixelRatio.get()).toBe(2); + expect(PixelRatio.getFontScale()).toBe(1.5); +}); + +it('updates native constraints on the UI thread before running JavaScript', () => { + const root = createRoot({ + viewportWidth: 120, + viewportHeight: 140, + devicePixelRatio: 2, + }); + const viewRef = createRef(); + Fantom.runTask(() => { + root.render( + + + , + ); + }); + const view = nullthrows(viewRef.current); + const previousDimensions = Dimensions.get('window'); + const changes = jest.fn(); + const subscription = Dimensions.addEventListener('change', changes); + + try { + Fantom.runOnUIThread(() => { + root.enqueueUpdateSurfaceConstraints({ + viewportWidth: 200, + viewportHeight: 240, + devicePixelRatio: 4, + fontScale: 1.5, + viewportOffsetX: 25, + viewportOffsetY: 35, + }); + }); + + const bounds = view.getBoundingClientRect(); + expect(bounds.x).toBe(25); + expect(bounds.y).toBe(35); + expect(bounds.width).toBe(200); + expect(bounds.height).toBe(240); + expect(Dimensions.get('window')).toBe(previousDimensions); + expect(changes).not.toHaveBeenCalled(); + expect(root.getRenderedOutput({props: ['testID']}).toJSX()).toEqual( + + + , + ); + + Fantom.runWorkLoop(); + + expect(changes).toHaveBeenCalledTimes(1); + expect(Dimensions.get('window')).toEqual({ + width: 200, + height: 240, + scale: 4, + fontScale: 1.5, + }); + expect(previousDimensions).toEqual({ + width: 120, + height: 140, + scale: 2, + fontScale: 1, + }); + expect(root.getRenderedOutput({props: ['testID']}).toJSX()).toEqual( + + + , + ); + expect(viewRef.current).toBe(view); + } finally { + subscription.remove(); + } +}); + +it('updates constraints within an existing JavaScript task without nesting the work loop', () => { + const root = createRoot({viewportWidth: 120, viewportHeight: 140}); + Fantom.runTask(() => root.render()); + + Fantom.runTask(() => { + root.updateSurfaceConstraints({viewportWidth: 200, fontScale: 1.5}); + expect(Dimensions.get('window').width).toBe(120); + }); + + expect(Dimensions.get('window')).toEqual({ + width: 200, + height: 140, + scale: 3, + fontScale: 1.5, + }); + expect(root.getRenderedOutput({props: ['testID']}).toJSX()).toEqual( + , + ); +}); + +it('merges queued partial updates without losing earlier native changes', () => { + const root = createRoot({ + viewportWidth: 120, + viewportHeight: 140, + devicePixelRatio: 2, + }); + const changes: Array = []; + const subscription = Dimensions.addEventListener('change', ({window}) => { + changes.push( + `${window.width}x${window.height}@${window.scale}:${window.fontScale}`, + ); + }); + + try { + Fantom.runOnUIThread(() => { + root.enqueueUpdateSurfaceConstraints({viewportWidth: 210}); + root.enqueueUpdateSurfaceConstraints({fontScale: 1.75}); + }); + expect(changes).toEqual([]); + + Fantom.runWorkLoop(); + + expect(changes).toEqual(['210x140@2:1', '210x140@2:1.75']); + expect(Dimensions.get('window')).toEqual({ + width: 210, + height: 140, + scale: 2, + fontScale: 1.75, + }); + } finally { + subscription.remove(); + } +}); + +it('applies pixel-ratio changes to native layout rounding', () => { + const root = createRoot({devicePixelRatio: 2}); + const viewRef = createRef(); + Fantom.runTask(() => { + root.render(); + }); + const view = nullthrows(viewRef.current); + expect(view.getBoundingClientRect().width).toBe(10.5); + expect(view.getBoundingClientRect().height).toBe(20.5); + + root.updateSurfaceConstraints({devicePixelRatio: 4}); + + expect(view.getBoundingClientRect().width).toBe(10.25); + expect(view.getBoundingClientRect().height).toBe(20.25); + expect(PixelRatio.get()).toBe(4); +}); + +it('updates existing dimensions without changing root creation order', () => { + const first = createRoot({viewportWidth: 100}); + const second = createRoot({viewportWidth: 200}); + const third = createRoot({viewportWidth: 300}); + expect(warn).toHaveBeenCalledTimes(2); + + first.updateSurfaceConstraints({viewportWidth: 400}); + + expect(warn).toHaveBeenCalledTimes(2); + third.destroy(); + roots.pop(); + expect(Dimensions.get('window').width).toBe(200); + second.destroy(); + roots.pop(); + expect(Dimensions.get('window').width).toBe(400); + first.destroy(); + roots.pop(); + expect(Dimensions.get('window').width).toBe(390); +}); + +it('does not restore dimensions from a queued update after root destruction', () => { + const root = createRoot({viewportWidth: 640}); + Fantom.runOnUIThread(() => { + root.enqueueUpdateSurfaceConstraints({viewportWidth: 900}); + }); + + root.destroy(); + roots.pop(); + + expect(Dimensions.get('window').width).toBe(390); + expect(() => + root.enqueueUpdateSurfaceConstraints({viewportWidth: 900}), + ).toThrow('Cannot update the constraints of a destroyed root.'); + createRoot(); + expect(warn).not.toHaveBeenCalled(); +}); + it('notifies mounted components when another root changes the metrics', () => { const first = createRoot(); Fantom.runTask(() => first.render()); diff --git a/private/react-native-fantom/src/index.js b/private/react-native-fantom/src/index.js index d58bdf8c783f..78175fbd772b 100644 --- a/private/react-native-fantom/src/index.js +++ b/private/react-native-fantom/src/index.js @@ -102,6 +102,17 @@ function pushDimensions( } } +function updateDimensions( + surfaceId: RootTag, + displayMetrics: DisplayMetrics, +): void { + if (!activeRootDisplayMetrics.has(surfaceId)) { + return; + } + activeRootDisplayMetrics.set(surfaceId, displayMetrics); + Dimensions.set({window: displayMetrics, screen: displayMetrics}); +} + function popDimensions(surfaceId: RootTag): void { activeRootDisplayMetrics.delete(surfaceId); const displayMetrics = Array.from(activeRootDisplayMetrics.values()).pop(); @@ -180,24 +191,76 @@ class Root { } } - takeMountingManagerLogs(): Array { - return NativeFantom.takeMountingManagerLogs(this.#surfaceId); + /** + * Updates native surface constraints and runs the pending JavaScript work. + * The width/height form only resizes the native surface without flushing work. + */ + updateSurfaceConstraints(config: RootConfig | number, height?: number): void { + if (typeof config === 'number') { + if (this.#destroyed) { + throw new Error('Cannot resize a destroyed root.'); + } + if (height == null) { + throw new Error('A height is required when resizing a root.'); + } + NativeFantom.updateSurfaceConstraints( + this.#surfaceId, + config, + height, + this.#devicePixelRatio, + ); + return; + } + + runOnUIThread(() => this.enqueueUpdateSurfaceConstraints(config)); + if (!flushingQueue) { + runWorkLoop(); + } } /** - * Changes the root's native surface constraints without rendering React, - * updating Dimensions, or flushing pending work. + * Updates native surface constraints without running JavaScript work. + * Call within `runOnUIThread` when batching UI-thread changes. */ - updateSurfaceConstraints(width: number, height: number): void { + enqueueUpdateSurfaceConstraints(config: RootConfig): void { if (this.#destroyed) { - throw new Error('Cannot resize a destroyed root.'); + throw new Error('Cannot update the constraints of a destroyed root.'); } + + const viewportWidth = config.viewportWidth ?? this.#viewportWidth; + const viewportHeight = config.viewportHeight ?? this.#viewportHeight; + const devicePixelRatio = config.devicePixelRatio ?? this.#devicePixelRatio; + const fontScale = config.fontScale ?? this.#fontScale; + const viewportOffsetX = config.viewportOffsetX ?? this.#viewportOffsetX; + const viewportOffsetY = config.viewportOffsetY ?? this.#viewportOffsetY; + NativeFantom.updateSurfaceConstraints( this.#surfaceId, - width, - height, - this.#devicePixelRatio, + viewportWidth, + viewportHeight, + devicePixelRatio, + fontScale, + viewportOffsetX, + viewportOffsetY, ); + this.#viewportWidth = viewportWidth; + this.#viewportHeight = viewportHeight; + this.#devicePixelRatio = devicePixelRatio; + this.#fontScale = fontScale; + this.#viewportOffsetX = viewportOffsetX; + this.#viewportOffsetY = viewportOffsetY; + + const displayMetrics = { + width: viewportWidth, + height: viewportHeight, + scale: devicePixelRatio, + fontScale, + }; + scheduleTask(() => updateDimensions(this.#surfaceId, displayMetrics)); + } + + takeMountingManagerLogs(): Array { + return NativeFantom.takeMountingManagerLogs(this.#surfaceId); } destroy() { diff --git a/private/react-native-fantom/tester/CMakeLists.txt b/private/react-native-fantom/tester/CMakeLists.txt index 62d1a1db5eb3..e25cc3b32d51 100644 --- a/private/react-native-fantom/tester/CMakeLists.txt +++ b/private/react-native-fantom/tester/CMakeLists.txt @@ -94,6 +94,7 @@ add_react_common_subdir(react/renderer/components/modal) add_react_common_subdir(react/renderer/components/root) add_react_common_subdir(react/renderer/components/scrollview) add_react_common_subdir(react/renderer/components/text) +add_react_common_subdir(react/renderer/components/textinput) add_react_common_subdir(react/renderer/components/view) add_react_common_subdir(react/renderer/consistency) add_react_common_subdir(react/renderer/core) @@ -146,7 +147,6 @@ file(GLOB SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/stubs/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/platform/oss/*.cpp ) -list(APPEND SOURCES ${REACT_COMMON_DIR}/react/renderer/components/textinput/BaseTextInputProps.cpp) add_executable(fantom_tester ${SOURCES}) target_include_directories(fantom_tester PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) @@ -236,6 +236,7 @@ target_link_libraries(fantom_tester rrc_root rrc_scrollview rrc_text + rrc_textinput rrc_view runtimeexecutor yogacore diff --git a/private/react-native-fantom/tester/react-common-tests/CMakeLists.txt b/private/react-native-fantom/tester/react-common-tests/CMakeLists.txt index 9a2114c96c3c..569155ee1764 100644 --- a/private/react-native-fantom/tester/react-common-tests/CMakeLists.txt +++ b/private/react-native-fantom/tester/react-common-tests/CMakeLists.txt @@ -20,19 +20,6 @@ add_react_common_subdir(react/networking) add_react_common_subdir(react/renderer/animations) add_react_common_subdir(react/renderer/element) -# rrc_textinput compiles the Android platform sources, which need the Android -# text layout; the tests only use the cross-platform base. -file(GLOB react_common_tests_textinput_SRC CONFIGURE_DEPENDS - ${REACT_COMMON_DIR}/react/renderer/components/textinput/*.cpp) -add_library(react_common_tests_textinput OBJECT ${react_common_tests_textinput_SRC}) -target_link_libraries(react_common_tests_textinput - PUBLIC - react_renderer_attributedstring - react_renderer_core - rrc_text - rrc_view) -target_compile_reactnative_options(react_common_tests_textinput PRIVATE) - # The folly executors some tests use, and what they pull in, which # folly_runtime leaves out. set(folly_DIR ${FANTOM_THIRD_PARTY_DIR}/folly/folly) @@ -111,7 +98,6 @@ foreach(test_dir ${react_common_tests_DIRS}) PRIVATE ${react_common_tests_LIBS} react_common_tests_folly - react_common_tests_textinput react_networking react_renderer_animations react_renderer_element diff --git a/private/react-native-fantom/tester/src/NativeFantom.cpp b/private/react-native-fantom/tester/src/NativeFantom.cpp index 487dbea094c7..c55e30e3f1e6 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.cpp +++ b/private/react-native-fantom/tester/src/NativeFantom.cpp @@ -56,21 +56,27 @@ SurfaceId NativeFantom::startSurface( return surfaceId; } -void NativeFantom::stopSurface(jsi::Runtime& /*runtime*/, SurfaceId surfaceId) { - appDelegate_.stopSurface(surfaceId); -} - void NativeFantom::updateSurfaceConstraints( jsi::Runtime& /*runtime*/, SurfaceId surfaceId, double viewportWidth, double viewportHeight, - double devicePixelRatio) { + double devicePixelRatio, + std::optional fontScale, + std::optional viewportOffsetX, + std::optional viewportOffsetY) { appDelegate_.updateSurfaceConstraints( surfaceId, static_cast(viewportWidth), static_cast(viewportHeight), - static_cast(devicePixelRatio)); + static_cast(devicePixelRatio), + static_cast(fontScale.value_or(1)), + static_cast(viewportOffsetX.value_or(0)), + static_cast(viewportOffsetY.value_or(0))); +} + +void NativeFantom::stopSurface(jsi::Runtime& /*runtime*/, SurfaceId surfaceId) { + appDelegate_.stopSurface(surfaceId); } void NativeFantom::produceFramesForDuration( diff --git a/private/react-native-fantom/tester/src/NativeFantom.h b/private/react-native-fantom/tester/src/NativeFantom.h index 90d677146703..12633921d1a9 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.h +++ b/private/react-native-fantom/tester/src/NativeFantom.h @@ -87,14 +87,17 @@ class NativeFantom : public NativeFantomCxxSpec { double viewportOffsetX, double viewportOffsetY); - void stopSurface(jsi::Runtime &runtime, SurfaceId surfaceId); - void updateSurfaceConstraints( jsi::Runtime &runtime, SurfaceId surfaceId, double viewportWidth, double viewportHeight, - double devicePixelRatio); + double devicePixelRatio, + std::optional fontScale, + std::optional viewportOffsetX, + std::optional viewportOffsetY); + + void stopSurface(jsi::Runtime &runtime, SurfaceId surfaceId); void produceFramesForDuration(jsi::Runtime &runtime, double milliseconds); diff --git a/private/react-native-fantom/tester/src/TesterAppDelegate.cpp b/private/react-native-fantom/tester/src/TesterAppDelegate.cpp index 7738540eabd0..a63c745d57a0 100644 --- a/private/react-native-fantom/tester/src/TesterAppDelegate.cpp +++ b/private/react-native-fantom/tester/src/TesterAppDelegate.cpp @@ -309,7 +309,10 @@ void TesterAppDelegate::updateSurfaceConstraints( SurfaceId surfaceId, float widthDp, float heightDp, - float pointScaleFactor) { + float pointScaleFactor, + float fontScale, + float viewportOffsetX, + float viewportOffsetY) { Size extentsDp{static_cast(widthDp), static_cast(heightDp)}; LayoutConstraints layoutConstraints{ .minimumSize = extentsDp, @@ -319,6 +322,8 @@ void TesterAppDelegate::updateSurfaceConstraints( LayoutContext layoutContext{ .pointScaleFactor = pointScaleFactor, + .fontSizeMultiplier = fontScale, + .viewportOffset = {.x = viewportOffsetX, .y = viewportOffsetY}, }; reactHost_->setSurfaceConstraints( diff --git a/private/react-native-fantom/tester/src/TesterAppDelegate.h b/private/react-native-fantom/tester/src/TesterAppDelegate.h index de349ba9af18..7eb622af0b15 100644 --- a/private/react-native-fantom/tester/src/TesterAppDelegate.h +++ b/private/react-native-fantom/tester/src/TesterAppDelegate.h @@ -68,7 +68,14 @@ class TesterAppDelegate { float viewportOffsetX = 0.0f, float viewportOffsetY = 0.0f); - void updateSurfaceConstraints(SurfaceId surfaceId, float widthDp, float heightDp, float pointScaleFactor); + void updateSurfaceConstraints( + SurfaceId surfaceId, + float widthDp, + float heightDp, + float pointScaleFactor, + float fontScale, + float viewportOffsetX, + float viewportOffsetY); void stopSurface(SurfaceId surfaceId);