Skip to content

Commit 0adb129

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: Fixes facebook#44157 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 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) Reviewed By: javache, philIip Differential Revision: D64121570
1 parent d287c72 commit 0adb129

File tree

4 files changed

+207
-6
lines changed

4 files changed

+207
-6
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: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,13 @@ @implementation RCTTextInputComponentView {
6161
*/
6262
BOOL _comingFromJS;
6363
BOOL _didMoveToWindow;
64+
65+
/*
66+
* Newly initialized default typing attributes contain a no-op NSParagraphStyle and NSShadow. These cause inequality
67+
* between the AttributedString backing the input and those generated from state. We store these attributes to make
68+
* later comparison insensitive to them.
69+
*/
70+
NSDictionary<NSAttributedStringKey, id> *_originalTypingAttributes;
6471
}
6572

6673
#pragma mark - UIView overrides
@@ -76,6 +83,7 @@ - (instancetype)initWithFrame:(CGRect)frame
7683
_ignoreNextTextInputCall = NO;
7784
_comingFromJS = NO;
7885
_didMoveToWindow = NO;
86+
_originalTypingAttributes = [_backedTextInputView.typingAttributes copy];
7987

8088
[self addSubview:_backedTextInputView];
8189
[self initializeReturnKeyType];
@@ -84,6 +92,20 @@ - (instancetype)initWithFrame:(CGRect)frame
8492
return self;
8593
}
8694

95+
- (void)updateEventEmitter:(const EventEmitter::Shared &)eventEmitter
96+
{
97+
[super updateEventEmitter:eventEmitter];
98+
99+
NSMutableDictionary<NSAttributedStringKey, id> *defaultAttributes =
100+
[_backedTextInputView.defaultTextAttributes mutableCopy];
101+
102+
RCTWeakEventEmitterWrapper *eventEmitterWrapper = [RCTWeakEventEmitterWrapper new];
103+
eventEmitterWrapper.eventEmitter = _eventEmitter;
104+
defaultAttributes[RCTAttributedStringEventEmitterKey] = eventEmitterWrapper;
105+
106+
_backedTextInputView.defaultTextAttributes = defaultAttributes;
107+
}
108+
87109
- (void)didMoveToWindow
88110
{
89111
[super didMoveToWindow];
@@ -236,8 +258,11 @@ - (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared &
236258
}
237259

238260
if (newTextInputProps.textAttributes != oldTextInputProps.textAttributes) {
239-
_backedTextInputView.defaultTextAttributes =
261+
NSMutableDictionary<NSAttributedStringKey, id> *defaultAttributes =
240262
RCTNSTextAttributesFromTextAttributes(newTextInputProps.getEffectiveTextAttributes(RCTFontSizeMultiplier()));
263+
defaultAttributes[RCTAttributedStringEventEmitterKey] =
264+
_backedTextInputView.defaultTextAttributes[RCTAttributedStringEventEmitterKey];
265+
_backedTextInputView.defaultTextAttributes = defaultAttributes;
241266
}
242267

243268
if (newTextInputProps.selectionColor != oldTextInputProps.selectionColor) {
@@ -732,9 +757,10 @@ - (BOOL)_textOf:(NSAttributedString *)newText equals:(NSAttributedString *)oldTe
732757
_backedTextInputView.markedTextRange || _backedTextInputView.isSecureTextEntry || fontHasBeenUpdatedBySystem;
733758

734759
if (shouldFallbackToBareTextComparison) {
735-
return ([newText.string isEqualToString:oldText.string]);
760+
return [newText.string isEqualToString:oldText.string];
736761
} else {
737-
return ([newText isEqualToAttributedString:oldText]);
762+
return RCTIsAttributedStringEffectivelySame(
763+
newText, oldText, _originalTypingAttributes, static_cast<const TextInputProps &>(*_props).textAttributes);
738764
}
739765
}
740766

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

Lines changed: 12 additions & 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
/*
@@ -41,6 +41,17 @@ NSString *RCTNSStringFromStringApplyingTextTransform(NSString *string, facebook:
4141

4242
void RCTApplyBaselineOffset(NSMutableAttributedString *attributedText);
4343

44+
/*
45+
* Whether two `NSAttributedString` lead to the same underlying displayed text, even if they are not strictly equal.
46+
* I.e. is one string substitutable for the other when backing a control (which may have some ignorable attributes
47+
* provided).
48+
*/
49+
BOOL RCTIsAttributedStringEffectivelySame(
50+
NSAttributedString *text1,
51+
NSAttributedString *text2,
52+
NSDictionary<NSAttributedStringKey, id> *insensitiveAttributes,
53+
const facebook::react::TextAttributes &baseTextAttributes);
54+
4455
@interface RCTWeakEventEmitterWrapper : NSObject
4556
@property (nonatomic, assign) facebook::react::SharedEventEmitter eventEmitter;
4657
@end

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

Lines changed: 165 additions & 2 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)
@@ -178,7 +196,8 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
178196
return effectiveBackgroundColor ?: [UIColor clearColor];
179197
}
180198

181-
NSDictionary<NSAttributedStringKey, id> *RCTNSTextAttributesFromTextAttributes(const TextAttributes &textAttributes)
199+
NSMutableDictionary<NSAttributedStringKey, id> *RCTNSTextAttributesFromTextAttributes(
200+
const TextAttributes &textAttributes)
182201
{
183202
NSMutableDictionary<NSAttributedStringKey, id> *attributes = [NSMutableDictionary dictionaryWithCapacity:10];
184203

@@ -302,7 +321,7 @@ inline static CGFloat RCTEffectiveFontSizeMultiplierFromTextAttributes(const Tex
302321
attributes[RCTTextAttributesAccessibilityRoleAttributeName] = [NSString stringWithUTF8String:roleStr.c_str()];
303322
}
304323

305-
return [attributes copy];
324+
return attributes;
306325
}
307326

308327
void RCTApplyBaselineOffset(NSMutableAttributedString *attributedText)
@@ -466,3 +485,147 @@ AttributedStringBox RCTAttributedStringBoxFromNSAttributedString(NSAttributedStr
466485
return string;
467486
}
468487
}
488+
489+
static BOOL RCTIsParagraphStyleEffectivelySame(
490+
NSParagraphStyle *style1,
491+
NSParagraphStyle *style2,
492+
const TextAttributes &baseTextAttributes)
493+
{
494+
if (style1 == nil || style2 == nil) {
495+
return style1 == nil && style2 == nil;
496+
}
497+
498+
// The NSParagraphStyle included as part of typingAttributes may eventually resolve "natural" directions to
499+
// physical direction, so we should compare resolved directions
500+
auto naturalAlignment =
501+
baseTextAttributes.layoutDirection.value_or(LayoutDirection::LeftToRight) == LayoutDirection::LeftToRight
502+
? NSTextAlignmentLeft
503+
: NSTextAlignmentRight;
504+
505+
NSWritingDirection naturalBaseWritingDirection = baseTextAttributes.baseWritingDirection.has_value()
506+
? RCTNSWritingDirectionFromWritingDirection(baseTextAttributes.baseWritingDirection.value())
507+
: [NSParagraphStyle defaultWritingDirectionForLanguage:nil];
508+
509+
if (style1.alignment == NSTextAlignmentNatural || style1.baseWritingDirection == NSWritingDirectionNatural) {
510+
NSMutableParagraphStyle *mutableStyle1 = [style1 mutableCopy];
511+
style1 = mutableStyle1;
512+
513+
if (mutableStyle1.alignment == NSTextAlignmentNatural) {
514+
mutableStyle1.alignment = naturalAlignment;
515+
}
516+
517+
if (mutableStyle1.baseWritingDirection == NSWritingDirectionNatural) {
518+
mutableStyle1.baseWritingDirection = naturalBaseWritingDirection;
519+
}
520+
}
521+
522+
if (style2.alignment == NSTextAlignmentNatural || style2.baseWritingDirection == NSWritingDirectionNatural) {
523+
NSMutableParagraphStyle *mutableStyle2 = [style2 mutableCopy];
524+
style2 = mutableStyle2;
525+
526+
if (mutableStyle2.alignment == NSTextAlignmentNatural) {
527+
mutableStyle2.alignment = naturalAlignment;
528+
}
529+
530+
if (mutableStyle2.baseWritingDirection == NSWritingDirectionNatural) {
531+
mutableStyle2.baseWritingDirection = naturalBaseWritingDirection;
532+
}
533+
}
534+
535+
return [style1 isEqual:style2];
536+
}
537+
538+
static BOOL RCTIsAttributeEffectivelySame(
539+
NSAttributedStringKey attributeKey,
540+
NSDictionary<NSAttributedStringKey, id> *attributes1,
541+
NSDictionary<NSAttributedStringKey, id> *attributes2,
542+
NSDictionary<NSAttributedStringKey, id> *insensitiveAttributes,
543+
const TextAttributes &baseTextAttributes)
544+
{
545+
id attribute1 = attributes1[attributeKey] ?: insensitiveAttributes[attributeKey];
546+
id attribute2 = attributes2[attributeKey] ?: insensitiveAttributes[attributeKey];
547+
548+
// Normalize attributes which can inexact but still effectively the same
549+
if ([attributeKey isEqualToString:NSParagraphStyleAttributeName]) {
550+
return RCTIsParagraphStyleEffectivelySame(attribute1, attribute2, baseTextAttributes);
551+
}
552+
553+
// Otherwise rely on built-in comparison
554+
return [attribute1 isEqual:attribute2];
555+
}
556+
557+
BOOL RCTIsAttributedStringEffectivelySame(
558+
NSAttributedString *text1,
559+
NSAttributedString *text2,
560+
NSDictionary<NSAttributedStringKey, id> *insensitiveAttributes,
561+
const TextAttributes &baseTextAttributes)
562+
{
563+
if (![text1.string isEqualToString:text2.string]) {
564+
return NO;
565+
}
566+
567+
// We check that for every fragment in the old string
568+
// 1. The new string's fragment overlapping the first spans the same characters
569+
// 2. The attributes of each matching fragment are the same, ignoring those which match insensitive attibutes
570+
__block BOOL areAttributesSame = YES;
571+
[text1 enumerateAttributesInRange:NSMakeRange(0, text1.length)
572+
options:0
573+
usingBlock:^(
574+
NSDictionary<NSAttributedStringKey, id> *text1Attributes,
575+
NSRange text1Range,
576+
BOOL *text1Stop) {
577+
[text2 enumerateAttributesInRange:text1Range
578+
options:0
579+
usingBlock:^(
580+
NSDictionary<NSAttributedStringKey, id> *text2Attributes,
581+
NSRange text2Range,
582+
BOOL *text2Stop) {
583+
if (!NSEqualRanges(text1Range, text2Range)) {
584+
areAttributesSame = NO;
585+
*text1Stop = YES;
586+
*text2Stop = YES;
587+
return;
588+
}
589+
590+
// Compare every attribute in text1 to the corresponding attribute
591+
// in text2, or the set of insensitive attributes if not present
592+
for (NSAttributedStringKey key in text1Attributes) {
593+
if (!RCTIsAttributeEffectivelySame(
594+
key,
595+
text1Attributes,
596+
text2Attributes,
597+
insensitiveAttributes,
598+
baseTextAttributes)) {
599+
areAttributesSame = NO;
600+
*text1Stop = YES;
601+
*text2Stop = YES;
602+
return;
603+
}
604+
}
605+
606+
for (NSAttributedStringKey key in text2Attributes) {
607+
// We have already compared this attribute if it is present in
608+
// both
609+
if (text1Attributes[key] != nil) {
610+
continue;
611+
}
612+
613+
// But we still need to compare attributes if it is only present
614+
// in text 2, to compare against insensitive attributes
615+
if (!RCTIsAttributeEffectivelySame(
616+
key,
617+
text1Attributes,
618+
text2Attributes,
619+
insensitiveAttributes,
620+
baseTextAttributes)) {
621+
areAttributesSame = NO;
622+
*text1Stop = YES;
623+
*text2Stop = YES;
624+
return;
625+
}
626+
}
627+
}];
628+
}];
629+
630+
return areAttributesSame;
631+
}

0 commit comments

Comments
 (0)