Skip to content

Commit cb9e1fe

Browse files
NickGerlemanfacebook-github-bot
authored andcommitted
Fix cursor moving while typing quickly and autocorrection triggered in controlled single line TextInput on iOS (New Arch) (facebook#46970)
Summary: This one is a bit of a doozy... During auto-correct in UITextField (used for single line TextInput) iOS will mutate the buffer in two parts, non-atomically. After the first part, after iOS triggers `textFieldDidChange`, selection is in the wrong position. If we set full new AttributedText at this point, we propagate the incorrect cursor position, and it is never restored. In the common case, where we are not mutating text in the controlled component, we shouldn't need to be setting AttributedString in the first place, and we do have an equality comparison there currently. But it is defeated because attributes are not identical. There are a few sources of that: 1. NSParagraphStyle is present in backing input, but not the AttributedString we are setting. 2. Backing text has an NSShadow with no color (does not render) not in the AttributedText 3. Event emitter attributes change on each update, and new text does not inherit the attributes. The first two are part of the backing input `typingAttributes`, even if we set a dictionary without them. To solve for them, we make attribute comparison insensitive to the attribute values in a default initialized control. There is code around here fully falling back to attribute insensitive comparison, which we would ideally fix to instead role into this "effective" attribute comparison. The event emitter attributes being misaligned is a real problem. We fix in a couple ways. 1. We treat the attribute values as equal if the backing event emitter is the same 2. We preserve attributes that we already set and want to expand as part of typingAttributes 3. We set paragraph level event emitter as a default attribute so the first typed character receives it After these fixes, scenario in facebook/react-native-website#4247 no longer repros in new arch. Typing in debug build also subjectively seems faster? (we are not doing second invalidation of the control on every keypress). Changes which do mutate content may be susceptible to the same style of issue, though on web/`react-dom` in Chrome, this seems to not try to preserve selection at all if the selection is uncontrolled, so this seems like less of an issue. I haven't yet looked at old arch, but my guess is we have similar issues there, and could be fixed in similar ways (though, we've been trying to avoid changing it as much as possible, and 0.76+ has new arch as default, so not sure if worth fixing in old impl as well if this is very long running issue). Changelog: [iOS][Fixed] - Fix cursor moving in iOS controlled single line TextInput on Autocorrection (New Arch) Differential Revision: D64121570
1 parent 2c45675 commit cb9e1fe

File tree

5 files changed

+180
-19
lines changed

5 files changed

+180
-19
lines changed

packages/react-native/Libraries/Text/TextInput/RCTBackedTextInputViewProtocol.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ NS_ASSUME_NONNULL_BEGIN
3535
@property (nonatomic, assign, readonly) CGFloat zoomScale;
3636
@property (nonatomic, assign, readonly) CGPoint contentOffset;
3737
@property (nonatomic, assign, readonly) UIEdgeInsets contentInset;
38+
@property (nullable, nonatomic, copy) NSDictionary<NSAttributedStringKey, id> *typingAttributes;
3839

3940
// This protocol disallows direct access to `selectedTextRange` property because
4041
// unwise usage of it can break the `delegate` behavior. So, we always have to

packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm

Lines changed: 149 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
#import <react/renderer/components/iostextinput/TextInputComponentDescriptor.h>
1111
#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
12+
#import <react/renderer/textlayoutmanager/RCTTextPrimitivesConversions.h>
1213
#import <react/renderer/textlayoutmanager/TextLayoutManager.h>
1314

1415
#import <React/RCTBackedTextInputViewProtocol.h>
@@ -61,6 +62,13 @@ @implementation RCTTextInputComponentView {
6162
*/
6263
BOOL _comingFromJS;
6364
BOOL _didMoveToWindow;
65+
66+
/*
67+
* Newly initialized default typing attributes contain a no-op NSParagraphStyle and NSShadow. These cause inequality
68+
* between the AttributedString backing the input and those generated from state. We store these attributes to make
69+
* later comparison insensitive to them.
70+
*/
71+
NSDictionary<NSAttributedStringKey, id> *_defaultTypingAttributes;
6472
}
6573

6674
#pragma mark - UIView overrides
@@ -79,11 +87,27 @@ - (instancetype)initWithFrame:(CGRect)frame
7987

8088
[self addSubview:_backedTextInputView];
8189
[self initializeReturnKeyType];
90+
91+
_defaultTypingAttributes = [_backedTextInputView.typingAttributes copy];
8292
}
8393

8494
return self;
8595
}
8696

97+
- (void)updateEventEmitter:(const EventEmitter::Shared &)eventEmitter
98+
{
99+
[super updateEventEmitter:eventEmitter];
100+
101+
NSMutableDictionary<NSAttributedStringKey, id> *defaultAttributes =
102+
[_backedTextInputView.defaultTextAttributes mutableCopy];
103+
104+
RCTWeakEventEmitterWrapper *eventEmitterWrapper = [RCTWeakEventEmitterWrapper new];
105+
eventEmitterWrapper.eventEmitter = _eventEmitter;
106+
defaultAttributes[RCTAttributedStringEventEmitterKey] = eventEmitterWrapper;
107+
108+
_backedTextInputView.defaultTextAttributes = defaultAttributes;
109+
}
110+
87111
- (void)didMoveToWindow
88112
{
89113
[super didMoveToWindow];
@@ -236,8 +260,11 @@ - (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared &
236260
}
237261

238262
if (newTextInputProps.textAttributes != oldTextInputProps.textAttributes) {
239-
_backedTextInputView.defaultTextAttributes =
263+
NSMutableDictionary<NSAttributedStringKey, id> *defaultAttributes =
240264
RCTNSTextAttributesFromTextAttributes(newTextInputProps.getEffectiveTextAttributes(RCTFontSizeMultiplier()));
265+
defaultAttributes[RCTAttributedStringEventEmitterKey] =
266+
_backedTextInputView.defaultTextAttributes[RCTAttributedStringEventEmitterKey];
267+
_backedTextInputView.defaultTextAttributes = [defaultAttributes copy];
241268
}
242269

243270
if (newTextInputProps.selectionColor != oldTextInputProps.selectionColor) {
@@ -418,6 +445,7 @@ - (void)textInputDidChange
418445

419446
- (void)textInputDidChangeSelection
420447
{
448+
[self _updateTypingAttributes];
421449
if (_comingFromJS) {
422450
return;
423451
}
@@ -674,9 +702,26 @@ - (void)_setAttributedString:(NSAttributedString *)attributedString
674702
[_backedTextInputView scrollRangeToVisible:NSMakeRange(offsetStart, 0)];
675703
}
676704
[self _restoreTextSelection];
705+
[self _updateTypingAttributes];
677706
_lastStringStateWasUpdatedWith = attributedString;
678707
}
679708

709+
// Ensure that newly typed text will inherit any custom attributes. We follow the logic of RN Android, where attributes
710+
// to the left of the cursor are copied into new text, unless we are at the start of the field, in which case we will
711+
// copy the attributes from text to the right. This allows consistency between backed input and new AttributedText
712+
// https://github.com/facebook/react-native/blob/3102a58df38d96f3dacef0530e4dbb399037fcd2/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/SetSpanOperation.kt#L30
713+
- (void)_updateTypingAttributes
714+
{
715+
if (_backedTextInputView.attributedText.length > 0) {
716+
NSUInteger offsetStart = [_backedTextInputView offsetFromPosition:_backedTextInputView.beginningOfDocument
717+
toPosition:_backedTextInputView.selectedTextRange.start];
718+
719+
NSUInteger samplePoint = offsetStart == 0 ? 0 : offsetStart - 1;
720+
_backedTextInputView.typingAttributes = [_backedTextInputView.attributedText attributesAtIndex:samplePoint
721+
effectiveRange:NULL];
722+
}
723+
}
724+
680725
- (void)_setMultiline:(BOOL)multiline
681726
{
682727
[_backedTextInputView removeFromSuperview];
@@ -706,6 +751,10 @@ - (void)_setShowSoftInputOnFocus:(BOOL)showSoftInputOnFocus
706751

707752
- (BOOL)_textOf:(NSAttributedString *)newText equals:(NSAttributedString *)oldText
708753
{
754+
if (![newText.string isEqualToString:oldText.string]) {
755+
return NO;
756+
}
757+
709758
// When the dictation is running we can't update the attributed text on the backed up text view
710759
// because setting the attributed string will kill the dictation. This means that we can't impose
711760
// the settings on a dictation.
@@ -732,10 +781,107 @@ - (BOOL)_textOf:(NSAttributedString *)newText equals:(NSAttributedString *)oldTe
732781
_backedTextInputView.markedTextRange || _backedTextInputView.isSecureTextEntry || fontHasBeenUpdatedBySystem;
733782

734783
if (shouldFallbackToBareTextComparison) {
735-
return ([newText.string isEqualToString:oldText.string]);
784+
return YES;
736785
} else {
737-
return ([newText isEqualToAttributedString:oldText]);
786+
return [self _areAttributesEffectivelyEqual:oldText newText:newText];
787+
}
788+
}
789+
790+
- (BOOL)_areAttributesEffectivelyEqual:(NSAttributedString *)oldText newText:(NSAttributedString *)newText
791+
{
792+
// We check that for every fragment in the old string
793+
// 1. A fragment of the same range exists in the new string
794+
// 2. The attributes of each matching fragment are the same, ignoring those which match the always set default typing
795+
// attributes
796+
__block BOOL areAttriubtesEqual = YES;
797+
[oldText enumerateAttributesInRange:NSMakeRange(0, oldText.length)
798+
options:0
799+
usingBlock:^(NSDictionary<NSAttributedStringKey, id> *attrs, NSRange range, BOOL *stop) {
800+
[newText
801+
enumerateAttributesInRange:range
802+
options:0
803+
usingBlock:^(
804+
NSDictionary<NSAttributedStringKey, id> *innerAttrs,
805+
NSRange innerRange,
806+
BOOL *innerStop) {
807+
if (!NSEqualRanges(range, innerRange)) {
808+
areAttriubtesEqual = NO;
809+
*innerStop = YES;
810+
*stop = YES;
811+
return;
812+
}
813+
814+
NSMutableDictionary<NSAttributedStringKey, id> *normAttrs =
815+
[attrs mutableCopy];
816+
NSMutableDictionary<NSAttributedStringKey, id> *normInnerAttrs =
817+
[innerAttrs mutableCopy];
818+
819+
__unused NSDictionary *currentTypingAttributes =
820+
_backedTextInputView.typingAttributes;
821+
__unused NSDictionary *defaultAttributes =
822+
_backedTextInputView.defaultTextAttributes;
823+
824+
for (NSAttributedStringKey key in _defaultTypingAttributes) {
825+
id defaultAttr = _defaultTypingAttributes[key];
826+
if ([normAttrs[key] isEqual:defaultAttr] ||
827+
(key == NSParagraphStyleAttributeName &&
828+
[self _areParagraphStylesEffectivelyEqual:normAttrs[key]
829+
other:defaultAttr])) {
830+
[normAttrs removeObjectForKey:key];
831+
}
832+
if ([normInnerAttrs[key] isEqual:defaultAttr] ||
833+
(key == NSParagraphStyleAttributeName &&
834+
[self _areParagraphStylesEffectivelyEqual:normInnerAttrs[key]
835+
other:defaultAttr])) {
836+
[normInnerAttrs removeObjectForKey:key];
837+
}
838+
}
839+
840+
if (![normAttrs isEqualToDictionary:normInnerAttrs]) {
841+
areAttriubtesEqual = NO;
842+
*innerStop = YES;
843+
*stop = YES;
844+
}
845+
}];
846+
}];
847+
848+
return areAttriubtesEqual;
849+
}
850+
851+
// The default NSParagraphStyle included as part of typingAttributes will eventually resolve "natural" directions to
852+
// physical direction, so we should compare resolved directions
853+
- (BOOL)_areParagraphStylesEffectivelyEqual:(NSParagraphStyle *)style1 other:(NSParagraphStyle *)style2
854+
{
855+
NSMutableParagraphStyle *mutableStyle1 = [style1 mutableCopy];
856+
NSMutableParagraphStyle *mutableStyle2 = [style2 mutableCopy];
857+
858+
const auto &textAttributes = static_cast<const TextInputProps &>(*_props).textAttributes;
859+
860+
auto layoutDirection = textAttributes.layoutDirection.value_or(LayoutDirection::LeftToRight);
861+
if (mutableStyle1.alignment == NSTextAlignmentNatural) {
862+
mutableStyle1.alignment =
863+
layoutDirection == LayoutDirection::LeftToRight ? NSTextAlignmentLeft : NSTextAlignmentRight;
864+
}
865+
if (mutableStyle2.alignment == NSTextAlignmentNatural) {
866+
mutableStyle2.alignment =
867+
layoutDirection == LayoutDirection::LeftToRight ? NSTextAlignmentLeft : NSTextAlignmentRight;
868+
}
869+
870+
auto baseWritingDirection = [&]() {
871+
if (textAttributes.baseWritingDirection.has_value()) {
872+
return RCTNSWritingDirectionFromWritingDirection(textAttributes.baseWritingDirection.value());
873+
} else {
874+
return [NSParagraphStyle defaultWritingDirectionForLanguage:nil];
875+
}
876+
}();
877+
if (mutableStyle1.baseWritingDirection == NSWritingDirectionNatural) {
878+
mutableStyle1.baseWritingDirection = baseWritingDirection;
738879
}
880+
if (mutableStyle2.baseWritingDirection == NSWritingDirectionNatural) {
881+
mutableStyle2.baseWritingDirection = baseWritingDirection;
882+
}
883+
884+
return [mutableStyle1 isEqual:mutableStyle2];
739885
}
740886

741887
- (SubmitBehavior)getSubmitBehavior

packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ NSString *const RCTTextAttributesAccessibilityRoleAttributeName = @"Accessibilit
2222
/*
2323
* Creates `NSTextAttributes` from given `facebook::react::TextAttributes`
2424
*/
25-
NSDictionary<NSAttributedStringKey, id> *RCTNSTextAttributesFromTextAttributes(
25+
NSMutableDictionary<NSAttributedStringKey, id> *RCTNSTextAttributesFromTextAttributes(
2626
const facebook::react::TextAttributes &textAttributes);
2727

2828
/*

packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTAttributedTextUtils.mm

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,24 @@ - (void)dealloc
3535
_weakEventEmitter.reset();
3636
}
3737

38+
- (BOOL)isEqual:(id)object
39+
{
40+
// We consider the underlying EventEmitter as the identity
41+
if (![object isKindOfClass:[self class]]) {
42+
return NO;
43+
}
44+
45+
auto thisEventEmitter = [self eventEmitter];
46+
auto otherEventEmitter = [((RCTWeakEventEmitterWrapper *)object) eventEmitter];
47+
return thisEventEmitter == otherEventEmitter;
48+
}
49+
50+
- (NSUInteger)hash
51+
{
52+
// We consider the underlying EventEmitter as the identity
53+
return (NSUInteger)_weakEventEmitter.lock().get();
54+
}
55+
3856
@end
3957

4058
inline static UIFontWeight RCTUIFontWeightFromInteger(NSInteger fontWeight)
@@ -156,7 +174,8 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
156174

157175
inline static UIColor *RCTEffectiveForegroundColorFromTextAttributes(const TextAttributes &textAttributes)
158176
{
159-
UIColor *effectiveForegroundColor = RCTUIColorFromSharedColor(textAttributes.foregroundColor) ?: [UIColor blackColor];
177+
UIColor *effectiveForegroundColor =
178+
RCTPlatformColorFromColor(*textAttributes.foregroundColor) ?: [UIColor blackColor];
160179

161180
if (!isnan(textAttributes.opacity)) {
162181
effectiveForegroundColor = [effectiveForegroundColor
@@ -168,7 +187,7 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
168187

169188
inline static UIColor *RCTEffectiveBackgroundColorFromTextAttributes(const TextAttributes &textAttributes)
170189
{
171-
UIColor *effectiveBackgroundColor = RCTUIColorFromSharedColor(textAttributes.backgroundColor);
190+
UIColor *effectiveBackgroundColor = RCTPlatformColorFromColor(*textAttributes.backgroundColor);
172191

173192
if (effectiveBackgroundColor && !isnan(textAttributes.opacity)) {
174193
effectiveBackgroundColor = [effectiveBackgroundColor
@@ -178,7 +197,8 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
178197
return effectiveBackgroundColor ?: [UIColor clearColor];
179198
}
180199

181-
NSDictionary<NSAttributedStringKey, id> *RCTNSTextAttributesFromTextAttributes(const TextAttributes &textAttributes)
200+
NSMutableDictionary<NSAttributedStringKey, id> *RCTNSTextAttributesFromTextAttributes(
201+
const TextAttributes &textAttributes)
182202
{
183203
NSMutableDictionary<NSAttributedStringKey, id> *attributes = [NSMutableDictionary dictionaryWithCapacity:10];
184204

@@ -256,7 +276,7 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
256276
NSUnderlineStyle style = RCTNSUnderlineStyleFromTextDecorationStyle(
257277
textAttributes.textDecorationStyle.value_or(TextDecorationStyle::Solid));
258278

259-
UIColor *textDecorationColor = RCTUIColorFromSharedColor(textAttributes.textDecorationColor);
279+
UIColor *textDecorationColor = RCTPlatformColorFromColor(*textAttributes.textDecorationColor);
260280

261281
// Underline
262282
if (textDecorationLineType == TextDecorationLineType::Underline ||
@@ -285,7 +305,7 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
285305
NSShadow *shadow = [NSShadow new];
286306
shadow.shadowOffset = CGSize{textShadowOffset.width, textShadowOffset.height};
287307
shadow.shadowBlurRadius = textAttributes.textShadowRadius;
288-
shadow.shadowColor = RCTUIColorFromSharedColor(textAttributes.textShadowColor);
308+
shadow.shadowColor = RCTPlatformColorFromColor(*textAttributes.textShadowColor);
289309
attributes[NSShadowAttributeName] = shadow;
290310
}
291311

@@ -302,7 +322,7 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
302322
attributes[RCTTextAttributesAccessibilityRoleAttributeName] = [NSString stringWithUTF8String:roleStr.c_str()];
303323
}
304324

305-
return [attributes copy];
325+
return attributes;
306326
}
307327

308328
void RCTApplyBaselineOffset(NSMutableAttributedString *attributedText)

packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/ios/react/renderer/textlayoutmanager/RCTTextPrimitivesConversions.h

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77

88
#import <UIKit/UIKit.h>
99

10-
#include <react/renderer/graphics/RCTPlatformColorUtils.h>
11-
#include <react/renderer/textlayoutmanager/RCTFontProperties.h>
12-
#include <react/renderer/textlayoutmanager/RCTFontUtils.h>
10+
#import <react/renderer/graphics/RCTPlatformColorUtils.h>
11+
#import <react/renderer/textlayoutmanager/RCTFontProperties.h>
12+
#import <react/renderer/textlayoutmanager/RCTFontUtils.h>
1313

1414
inline static NSTextAlignment RCTNSTextAlignmentFromTextAlignment(facebook::react::TextAlignment textAlignment)
1515
{
@@ -112,9 +112,3 @@ inline static NSUnderlineStyle RCTNSUnderlineStyleFromTextDecorationStyle(
112112
return NSUnderlinePatternDot | NSUnderlineStyleSingle;
113113
}
114114
}
115-
116-
// TODO: this file has some duplicates method, we can remove it
117-
inline static UIColor *_Nullable RCTUIColorFromSharedColor(const facebook::react::SharedColor &sharedColor)
118-
{
119-
return RCTPlatformColorFromColor(*sharedColor);
120-
}

0 commit comments

Comments
 (0)