Skip to content

Commit

Permalink
Prevent spurious onBlur/onEndEditing events in <TextInput> elements…
Browse files Browse the repository at this point in the history
… with placeholder text (microsoft#2160)

* Add _isUpdatingPlaceholderText to prevent spurious "did end editing" notifications

* Organize macOS tags and ifdef blocks

---------

Co-authored-by: Adam Gleitman <[email protected]>
  • Loading branch information
amgleitman and Adam Gleitman authored Aug 19, 2024
1 parent 6785f6d commit a44c574
Showing 1 changed file with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ @implementation RCTUITextField {
#endif
RCTBackedTextFieldDelegateAdapter *_textInputDelegateAdapter;
NSDictionary<NSAttributedStringKey, id> *_defaultTextAttributes;
#if TARGET_OS_OSX // [macOS
BOOL _isUpdatingPlaceholderText;
#endif // macOS]
}

#if TARGET_OS_OSX // [macOS
Expand All @@ -116,6 +119,9 @@ - (instancetype)initWithFrame:(CGRect)frame

_textInputDelegateAdapter = [[RCTBackedTextFieldDelegateAdapter alloc] initWithTextField:self];
_scrollEnabled = YES;
#if TARGET_OS_OSX // [macOS
_isUpdatingPlaceholderText = NO;
#endif // macOS]
}

return self;
Expand Down Expand Up @@ -361,8 +367,11 @@ - (void)_updatePlaceholder
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder ?: @""
attributes:[self _placeholderTextAttributes]];
#else // [macOS
// Set _isUpdatingPlaceholderText to manually suppress RCTUITextFieldDelegate's textFieldEndEditing
_isUpdatingPlaceholderText = YES;
self.placeholderAttributedString = [[NSAttributedString alloc] initWithString:self.placeholder ?: @""
attributes:[self _placeholderTextAttributes]];
_isUpdatingPlaceholderText = NO;
#endif // macOS]
}

Expand Down Expand Up @@ -485,10 +494,17 @@ - (void)textDidChange:(NSNotification *)notification
[delegate textFieldDidChange:self];
}
}

- (void)textDidEndEditing:(NSNotification *)notification
{
[super textDidEndEditing:notification];
[super textDidEndEditing:notification];

// On macOS, setting placeholderAttributedString causes AppKit to call textDidEndEditing.
// We don't want this to propagate or else we get unexpected onBlur/onEndEditing events.
if (_isUpdatingPlaceholderText) {
return;
}

id<RCTUITextFieldDelegate> delegate = self.delegate;
if ([delegate respondsToSelector:@selector(textFieldEndEditing:)]) {
[delegate textFieldEndEditing:self];
Expand Down

0 comments on commit a44c574

Please sign in to comment.