diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm index e042d4868a0f..cf1d0700099f 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm @@ -62,6 +62,8 @@ @implementation RCTTextInputComponentView { UIView *_backedTextInputView; NSUInteger _mostRecentEventCount; NSAttributedString *_lastStringStateWasUpdatedWith; + // The React styles currently applied to the multiline input. + NSAttributedString *_lastAppliedMultilineReactText; /* * UIKit uses either UITextField or UITextView as its UIKit element for . UITextField is for single line @@ -364,6 +366,7 @@ - (void)updateState:(const State::Shared &)state oldState:(const State::Shared & if (!_state) { assert(false && "State is `null` for component."); + _lastAppliedMultilineReactText = nil; _backedTextInputView.attributedText = nil; return; } @@ -376,11 +379,23 @@ - (void)updateState:(const State::Shared &)state oldState:(const State::Shared & if (_mostRecentEventCount == _state->getData().mostRecentEventCount) { NSAttributedString *attributedString = RCTNSAttributedStringFromAttributedStringBox(data.attributedStringBox); - if (![attributedString.string isEqualToString:_backedTextInputView.attributedText.string]) { + NSAttributedString *nativeText = _backedTextInputView.attributedText; + BOOL sameText = [attributedString.string isEqualToString:nativeText.string]; + if (!sameText) { [_backedTextInputView rct_invalidatePendingTextInputEdit]; } _comingFromJS = YES; - [self _setAttributedString:attributedString]; + BOOL tracksReactStyle = [_backedTextInputView isKindOfClass:[RCTUITextView class]] && + data.attributedStringBox.getMode() == AttributedStringBox::Mode::Value; + if (!(sameText && tracksReactStyle && + [self _applyMultilineStyleUpdate:attributedString previousReactText:_lastAppliedMultilineReactText])) { + if ([self _setAttributedString:attributedString]) { + _lastAppliedMultilineReactText = tracksReactStyle ? attributedString : nil; + } else if ( + sameText && tracksReactStyle && [self _multilineReactText:attributedString matchesNativeText:nativeText]) { + _lastAppliedMultilineReactText = attributedString; + } + } _comingFromJS = NO; } } @@ -410,6 +425,7 @@ - (void)prepareForRecycle _mostRecentEventCount = 0; _comingFromJS = NO; _lastStringStateWasUpdatedWith = nil; + _lastAppliedMultilineReactText = nil; _ignoreNextTextInputCall = NO; _didMoveToWindow = NO; _backedTextInputView.inputAccessoryViewID = nil; @@ -629,6 +645,7 @@ - (void)focus const auto &props = static_cast(*_props); if (props.traits.clearTextOnFocus) { + _lastAppliedMultilineReactText = nil; _backedTextInputView.attributedText = nil; [self textInputDidChange]; } @@ -659,7 +676,9 @@ - (void)setTextAndSelection:(NSInteger)eventCount if (value && ![value isEqualToString:_backedTextInputView.attributedText.string]) { NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:value attributes:_backedTextInputView.defaultTextAttributes]; - [self _setAttributedString:attributedString]; + if ([self _setAttributedString:attributedString]) { + _lastAppliedMultilineReactText = nil; + } [self _updateState]; } @@ -809,6 +828,10 @@ - (void)_updateState return; } NSAttributedString *attributedString = _backedTextInputView.attributedText; + if (_lastAppliedMultilineReactText && + ![_lastAppliedMultilineReactText.string isEqualToString:attributedString.string]) { + _lastAppliedMultilineReactText = nil; + } auto data = _state->getData(); _lastStringStateWasUpdatedWith = attributedString; data.attributedStringBox = RCTAttributedStringBoxFromNSAttributedString(attributedString); @@ -848,10 +871,10 @@ - (void)_restoreTextSelectionAndIgnoreCaretChange:(BOOL)ignore [_backedTextInputView setSelectedTextRange:range notifyDelegate:YES]; } -- (void)_setAttributedString:(NSAttributedString *)attributedString +- (BOOL)_setAttributedString:(NSAttributedString *)attributedString { if ([self _textOf:attributedString equals:_backedTextInputView.attributedText]) { - return; + return NO; } UITextRange *selectedRange = _backedTextInputView.selectedTextRange; NSInteger oldTextLength = _backedTextInputView.attributedText.string.length; @@ -882,6 +905,98 @@ - (void)_setAttributedString:(NSAttributedString *)attributedString [self _restoreTextSelectionAndIgnoreCaretChange:YES]; [self _updateTypingAttributes]; _lastStringStateWasUpdatedWith = attributedString; + return YES; +} + +- (BOOL)_multilineReactText:(NSAttributedString *)text matchesNativeText:(NSAttributedString *)nativeText +{ + if ([self _shouldCompareTextWithoutAttributes]) { + return NO; + } + + // A native edit can leave UIKit's fallback font on a React text echo. + __block NSMutableAttributedString *comparableText = nil; + [nativeText enumerateAttribute:@"NSOriginalFont" + inRange:NSMakeRange(0, nativeText.length) + options:0 + usingBlock:^(id font, NSRange range, BOOL *stop) { + if (font) { + if (!comparableText) { + comparableText = [nativeText mutableCopy]; + } + [comparableText addAttribute:NSFontAttributeName value:font range:range]; + [comparableText removeAttribute:@"NSOriginalFont" range:range]; + } + }]; + return RCTIsAttributedStringEffectivelySame( + text, + comparableText ?: nativeText, + _originalTypingAttributes, + static_cast(*_props).textAttributes); +} + +- (BOOL)_applyMultilineStyleUpdate:(NSAttributedString *)text previousReactText:(NSAttributedString *)previousReactText +{ + if (![text.string isEqualToString:previousReactText.string]) { + return NO; + } + if ([self _shouldCompareTextWithoutAttributes]) { + return YES; + } + + RCTUITextView *textView = (RCTUITextView *)_backedTextInputView; + NSTextStorage *storage = textView.textStorage; + NSRange selection = textView.selectedRange; + CGPoint contentOffset = textView.contentOffset; + BOOL edited = NO; + [storage beginEditing]; + // Compare two React snapshots so UIKit's fallback fonts and transient attributes do not cause an edit. + for (NSUInteger location = 0; location < text.length;) { + NSRange remaining = NSMakeRange(location, text.length - location); + NSRange currentRange; + NSRange previousRange; + NSDictionary *attributes = [text attributesAtIndex:location + longestEffectiveRange:¤tRange + inRange:remaining]; + NSDictionary *previousAttributes = [previousReactText attributesAtIndex:location + longestEffectiveRange:&previousRange + inRange:remaining]; + NSRange range = NSIntersectionRange(currentRange, previousRange); + + for (NSAttributedStringKey key in attributes) { + if ([key isEqualToString:RCTAttributedStringEventEmitterKey] || + [attributes[key] isEqual:previousAttributes[key]]) { + continue; + } + if ([key isEqualToString:NSFontAttributeName]) { + [storage removeAttribute:@"NSOriginalFont" range:range]; + } + [storage addAttribute:key value:attributes[key] range:range]; + edited = YES; + } + for (NSAttributedStringKey key in previousAttributes) { + if (attributes[key] == nil && ![key isEqualToString:RCTAttributedStringEventEmitterKey]) { + [storage removeAttribute:key range:range]; + edited = YES; + } + } + location = NSMaxRange(range); + } + [storage endEditing]; + + if (edited) { + if (selection.location != NSNotFound && !NSEqualRanges(selection, textView.selectedRange)) { + textView.selectedRange = selection; + } + [self _restoreTextSelection]; + if (!CGPointEqualToPoint(contentOffset, textView.contentOffset)) { + textView.contentOffset = contentOffset; + } + [self _updateTypingAttributes]; + _lastStringStateWasUpdatedWith = textView.attributedText; + } + _lastAppliedMultilineReactText = text; + return YES; } // Ensure that newly typed text will inherit any custom attributes. We follow the logic of RN Android, where attributes @@ -912,6 +1027,7 @@ - (void)scrollCursorIntoView - (void)_setMultiline:(BOOL)multiline { + _lastAppliedMultilineReactText = nil; [_backedTextInputView removeFromSuperview]; UIView *backedTextInputView = multiline ? [RCTUITextView new] : [RCTUITextField new]; @@ -938,7 +1054,7 @@ - (void)_setShowSoftInputOnFocus:(BOOL)showSoftInputOnFocus } } -- (BOOL)_textOf:(NSAttributedString *)newText equals:(NSAttributedString *)oldText +- (BOOL)_shouldCompareTextWithoutAttributes { // When the dictation is running we can't update the attributed text on the backed up text view // because setting the attributed string will kill the dictation. This means that we can't impose @@ -947,9 +1063,15 @@ - (BOOL)_textOf:(NSAttributedString *)newText equals:(NSAttributedString *)oldTe // text that we should disregard. See // https://developer.apple.com/documentation/uikit/uitextinput/1614489-markedtextrange?language=objc for more info. // Also, updating the attributed text while inputting Korean language will break input mechanism. - // If the user added an emoji, the system adds a font attribute for the emoji and stores the original font in - // NSOriginalFont. Lastly, when entering a password, etc., there will be additional styling on the field as the native - // text view handles showing the last character for a split second. + // Secure text entry adds styling while showing the last character for a split second. + return [_backedTextInputView.textInputMode.primaryLanguage isEqualToString:@"dictation"] || + [_backedTextInputView.textInputMode.primaryLanguage isEqualToString:@"ko-KR"] || + _backedTextInputView.markedTextRange || _backedTextInputView.isSecureTextEntry; +} + +- (BOOL)_textOf:(NSAttributedString *)newText equals:(NSAttributedString *)oldText +{ + // When UIKit substitutes a fallback font, it stores the requested font under NSOriginalFont. __block BOOL fontHasBeenUpdatedBySystem = false; [oldText enumerateAttribute:@"NSOriginalFont" inRange:NSMakeRange(0, oldText.length) @@ -960,12 +1082,7 @@ - (BOOL)_textOf:(NSAttributedString *)newText equals:(NSAttributedString *)oldTe } }]; - BOOL shouldFallbackToBareTextComparison = - [_backedTextInputView.textInputMode.primaryLanguage isEqualToString:@"dictation"] || - [_backedTextInputView.textInputMode.primaryLanguage isEqualToString:@"ko-KR"] || - _backedTextInputView.markedTextRange || _backedTextInputView.isSecureTextEntry || fontHasBeenUpdatedBySystem; - - if (shouldFallbackToBareTextComparison) { + if ([self _shouldCompareTextWithoutAttributes] || fontHasBeenUpdatedBySystem) { return [newText.string isEqualToString:oldText.string]; } else { return RCTIsAttributedStringEffectivelySame( diff --git a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj index f0a5f5305351..98106fdaebe3 100644 --- a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj +++ b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj @@ -17,6 +17,7 @@ 602160B9478DAFF2BAB56595 /* RCTUtilsTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D5D13FB1445C5C19639921CC /* RCTUtilsTests.m */; }; 79B29C2E2E607A99007612A5 /* SceneDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 79B29C2D2E607A99007612A5 /* SceneDelegate.mm */; }; 7F806D4D4D97AD6403558B35 /* RCTStatusBarAppearanceTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 67B0814814F7C07E196BC295 /* RCTStatusBarAppearanceTests.mm */; }; + FB66101562BC48A6B52F9860 /* RCTTextInputComponentViewTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3CC79368B7744ABBB0DCABBC /* RCTTextInputComponentViewTests.mm */; }; A8717727467541429C262C63 /* RCTTimingClockChangeTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = A8717727467541429C262C64 /* RCTTimingClockChangeTests.mm */; }; 8145AE06241172D900A3F8DA /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8145AE05241172D900A3F8DA /* LaunchScreen.storyboard */; }; 832F45BB2A8A6E1F0097B4E6 /* SwiftTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 832F45BA2A8A6E1F0097B4E6 /* SwiftTest.swift */; }; @@ -91,6 +92,7 @@ 51BC9297B6C3163C14532020 /* Pods-RNTester.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RNTester.release.xcconfig"; path = "Target Support Files/Pods-RNTester/Pods-RNTester.release.xcconfig"; sourceTree = ""; }; 5C60EB1B226440DB0018C04F /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = RNTester/AppDelegate.mm; sourceTree = ""; }; 67B0814814F7C07E196BC295 /* RCTStatusBarAppearanceTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RCTStatusBarAppearanceTests.mm; sourceTree = ""; }; + 3CC79368B7744ABBB0DCABBC /* RCTTextInputComponentViewTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RCTTextInputComponentViewTests.mm; sourceTree = ""; }; A8717727467541429C262C64 /* RCTTimingClockChangeTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RCTTimingClockChangeTests.mm; sourceTree = ""; }; 79B29C2C2E607A99007612A5 /* SceneDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SceneDelegate.h; path = RNTester/SceneDelegate.h; sourceTree = ""; }; 79B29C2D2E607A99007612A5 /* SceneDelegate.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = SceneDelegate.mm; path = RNTester/SceneDelegate.mm; sourceTree = ""; }; @@ -323,6 +325,7 @@ D5D13FB1445C5C19639921CC /* RCTUtilsTests.m */, E7DB20B322B2BAA4005AC45F /* RNTesterUnitTestsBundle.js */, 67B0814814F7C07E196BC295 /* RCTStatusBarAppearanceTests.mm */, + 3CC79368B7744ABBB0DCABBC /* RCTTextInputComponentViewTests.mm */, A8717727467541429C262C64 /* RCTTimingClockChangeTests.mm */, ); path = RNTesterUnitTests; @@ -644,6 +647,7 @@ E7DB20D822B2BAA6005AC45F /* RCTJSONTests.m in Sources */, 602160B9478DAFF2BAB56595 /* RCTUtilsTests.m in Sources */, 7F806D4D4D97AD6403558B35 /* RCTStatusBarAppearanceTests.mm in Sources */, + FB66101562BC48A6B52F9860 /* RCTTextInputComponentViewTests.mm in Sources */, A8717727467541429C262C63 /* RCTTimingClockChangeTests.mm in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/packages/rn-tester/RNTesterUnitTests/RCTTextInputComponentViewTests.mm b/packages/rn-tester/RNTesterUnitTests/RCTTextInputComponentViewTests.mm new file mode 100644 index 000000000000..ac5590c2145e --- /dev/null +++ b/packages/rn-tester/RNTesterUnitTests/RCTTextInputComponentViewTests.mm @@ -0,0 +1,203 @@ +/* + * 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 + +using namespace facebook::react; + +static TextInputShadowNode::ConcreteState::Shared textState( + AttributedString text, + const TextInputShadowNode::ConcreteState::Shared &previous = nullptr, + int64_t eventCount = 0) +{ + auto data = + std::make_shared(AttributedStringBox{text}, text, ParagraphAttributes{}, eventCount); + if (previous) { + return std::make_shared(data, *previous); + } + return std::make_shared(data, ShadowNodeFamily::Weak{}); +} + +static RCTTextInputComponentView *multilineInput() +{ + RCTTextInputComponentView *component = [[RCTTextInputComponentView alloc] initWithFrame:CGRectMake(0, 0, 300, 100)]; + auto props = std::make_shared(); + props->multiline = true; + [component updateProps:props oldProps:nullptr]; + return component; +} + +static AttributedString styledText(bool highlightFirst, bool split = true) +{ + TextAttributes first; + first.foregroundColor = highlightFirst ? colorFromRGBA(255, 0, 0, 255) : blackColor(); + if (!highlightFirst) { + first.textDecorationLineType = TextDecorationLineType::Underline; + } + AttributedString text; + text.appendFragment({.string = "Hello", .textAttributes = first}); + if (split) { + TextAttributes last; + last.foregroundColor = colorFromRGBA(0, 0, 255, 255); + text.appendFragment({.string = " ✅ world", .textAttributes = last}); + } else { + text.appendFragment({.string = " ✅ world", .textAttributes = first}); + } + return text; +} + +@interface RCTTextInputFontFallbackView : RCTUITextView +@end + +@implementation RCTTextInputFontFallbackView + +- (NSAttributedString *)attributedText +{ + // Simulate the font attributes reported by UIKit without depending on the simulator's font fallback. + NSMutableAttributedString *text = [[super attributedText] mutableCopy]; + NSRange emoji = [text.string rangeOfString:@"✅"]; + if (text.length == 0 || emoji.location == NSNotFound) { + return text; + } + UIFont *font = [text attribute:NSFontAttributeName atIndex:emoji.location effectiveRange:NULL]; + UIFont *fallback = [UIFont fontWithName:@"AppleColorEmoji" size:font.pointSize]; + if (font && fallback) { + [text addAttributes:@{@"NSOriginalFont" : font, NSFontAttributeName : fallback} range:emoji]; + } + return text; +} + +@end + +@interface RCTTextInputComponentViewTests : XCTestCase +@end + +@implementation RCTTextInputComponentViewTests + +- (void)testMultilineStyleUpdatePreservesSelectionAndUIKitFontFallback +{ + RCTTextInputComponentView *component = multilineInput(); + RCTUITextView *textView = (RCTUITextView *)component.accessibilityElement; + auto initial = textState(styledText(false)); + [component updateState:initial oldState:nullptr]; + + BOOL usesTextKit2 = NO; + if (@available(iOS 16.0, *)) { + usesTextKit2 = textView.textLayoutManager != nil; + } + NSTextStorage *storage = textView.textStorage; + NSString *string = [storage.string copy]; + NSRange emoji = [string rangeOfString:@"✅"]; + UIFont *originalFont = [storage attribute:NSFontAttributeName atIndex:emoji.location effectiveRange:NULL]; + [textView setSelectedRange:NSMakeRange(0, 5)]; + object_setClass(textView, [RCTTextInputFontFallbackView class]); + XCTAssertEqualObjects( + [textView.attributedText attribute:@"NSOriginalFont" atIndex:emoji.location effectiveRange:NULL], originalFont); + + auto updated = textState(styledText(true), initial); + [component updateState:updated oldState:initial]; + + XCTAssertEqual(storage, textView.textStorage); + if (@available(iOS 16.0, *)) { + XCTAssertEqual(usesTextKit2, textView.textLayoutManager != nil); + } + XCTAssertEqualObjects(textView.attributedText.string, string); + XCTAssertTrue(NSEqualRanges(textView.selectedRange, NSMakeRange(0, 5))); + XCTAssertEqualObjects( + [storage attribute:NSForegroundColorAttributeName atIndex:0 effectiveRange:NULL], UIColor.redColor); + XCTAssertNil([storage attribute:NSUnderlineStyleAttributeName atIndex:0 effectiveRange:NULL]); + XCTAssertEqualObjects( + [storage attribute:NSForegroundColorAttributeName atIndex:emoji.location effectiveRange:NULL], UIColor.blueColor); + XCTAssertEqualObjects( + [storage attribute:NSFontAttributeName atIndex:emoji.location effectiveRange:NULL], originalFont); +} + +- (void)testEquivalentReactStylesLeaveNativeStorageUntouched +{ + RCTTextInputComponentView *component = multilineInput(); + RCTUITextView *textView = (RCTUITextView *)component.accessibilityElement; + auto text = styledText(false, false); + auto initial = textState(text); + [component updateState:initial oldState:nullptr]; + + NSTextStorage *storage = textView.textStorage; + [textView setSelectedRange:NSMakeRange(2, 3)]; + [storage addAttribute:@"EventEmitter" value:@1 range:NSMakeRange(0, 5)]; + NSAttributedString *snapshot = [storage copy]; + + // The second native range has the same rendered style but a different React event target. + text.getFragments().back().parentShadowView.componentHandle = 1; + auto updated = textState(text, initial); + [component updateState:updated oldState:initial]; + + XCTAssertEqualObjects(storage, snapshot); + XCTAssertTrue(NSEqualRanges(textView.selectedRange, NSMakeRange(2, 3))); +} + +- (void)testMultilineStyleUpdateAfterNativeTextEchoWithFallback +{ + RCTTextInputComponentView *component = multilineInput(); + RCTUITextView *textView = (RCTUITextView *)component.accessibilityElement; + auto text = styledText(false, false); + text.getFragments().pop_back(); + auto initial = textState(text); + [component updateState:initial oldState:nullptr]; + + NSMutableAttributedString *nativeText = [textView.attributedText mutableCopy]; + [nativeText appendAttributedString:[[NSAttributedString alloc] initWithString:@" ✅ world" + attributes:[nativeText attributesAtIndex:0 + effectiveRange:NULL]]]; + textView.attributedText = nativeText; + object_setClass(textView, [RCTTextInputFontFallbackView class]); + XCTAssertNotNil([textView.attributedText attribute:@"NSOriginalFont" atIndex:6 effectiveRange:NULL]); + + auto echo = textState(styledText(false, false), initial, 1); + [component updateState:echo oldState:initial]; + auto updated = textState(styledText(true, false), echo, 1); + [component updateState:updated oldState:echo]; + + XCTAssertEqualObjects( + [textView.textStorage attribute:NSForegroundColorAttributeName atIndex:0 effectiveRange:NULL], UIColor.redColor); +} + +- (void)testMultilineStyleUpdateIgnoresStaleState +{ + RCTTextInputComponentView *component = multilineInput(); + RCTUITextView *textView = (RCTUITextView *)component.accessibilityElement; + TextAttributes attributes; + attributes.foregroundColor = blackColor(); + AttributedString text; + text.appendFragment({.string = "Hello world", .textAttributes = attributes}); + auto initial = textState(text, nullptr, 1); + [component updateState:initial oldState:nullptr]; + + NSAttributedString *snapshot = [textView.attributedText copy]; + auto &fragment = text.getFragments().front(); + fragment.textAttributes.foregroundColor = colorFromRGBA(255, 0, 0, 255); + auto stale = textState(text, initial, 0); + [component updateState:stale oldState:initial]; + + XCTAssertEqualObjects(textView.attributedText, snapshot); + + fragment.textAttributes.textDecorationLineType = TextDecorationLineType::Underline; + auto updated = textState(text, stale, 1); + [component updateState:updated oldState:stale]; + + NSTextStorage *storage = textView.textStorage; + XCTAssertEqualObjects( + [storage attribute:NSForegroundColorAttributeName atIndex:0 effectiveRange:NULL], UIColor.redColor); + XCTAssertEqualObjects( + [storage attribute:NSUnderlineStyleAttributeName atIndex:0 effectiveRange:NULL], @(NSUnderlineStyleSingle)); +} + +@end