react-native-macos/Libraries/Text/TextInput/RCTBaseTextInputShadowView.m

317 строки
9.2 KiB
Mathematica
Исходник Обычный вид История

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "RCTBaseTextInputShadowView.h"
#import <React/RCTBridge.h>
#import <React/RCTShadowView+Layout.h>
#import <React/RCTUIManager.h>
#import <yoga/Yoga.h>
#import "NSTextStorage+FontScaling.h"
#import "RCTBaseTextInputView.h"
@implementation RCTBaseTextInputShadowView
{
__weak RCTBridge *_bridge;
NSAttributedString *_Nullable _previousAttributedText;
BOOL _needsUpdateView;
NSAttributedString *_Nullable _localAttributedText;
CGSize _previousContentSize;
Fix #18272 TextInput.setNativeProps({text: ''}) to work (#18278) Summary: Fix #18272. Calling textInputRef.setNativeProps({text: ''}) or textInputRef.clear() should clear the text input. - All tests of `yarn run test` are passed - Test with [the sample app](https://github.com/magicien/react-native-textinput-clear). - TextInput.clear() and TextInput.setNativeProps({ text: '***' }) worked - When clear() or setNativeProps() called, onChange/onChangeText wasn't called - Same behavior as react 0.53.0 - When non-string values are given to `setNativeProps({text: ___})`, its behavior is the same as react 0.53.0. - Value Type | Result ---------- | ------------ null | same as empty string '' undefined | nothing changes number | throw error function | throw error object | throw error - When clear() or setNativeProps() called, attributed text keeps the attributes - When `value` prop is set, the text can't be changed - `clear()` doesn't work from the second time - `setNativeProps({text '***'})` doesn't work from the second time - Even when `value` prop is set, you can change the text ![ScreenShot_0.54.0](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/0.54.0_test.gif) - `clear()` works every time - `setNativeProps({text '****'})` works every time ![ScreenShot_Clear_1](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/clear_test_1.gif) ![ScreenShot_Clear_2](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/clear_test_2.gif) - The text keeps the attributes (font family, size, color, text align) ![ScreenShot_Slider](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/attributed_text_test.gif) - If `value` prop is set, the text should not be changed ![ScreenShot_Value](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/value_test.gif) [IOS] [BUGFIX] [TextInput] - Fix TextInput.clear() and TextInput.setNativeProps({text: ''}) to work Pull Request resolved: https://github.com/facebook/react-native/pull/18278 Reviewed By: shergin Differential Revision: D9692561 Pulled By: hramos fbshipit-source-id: b7ce8f6740fdf666e71d6a85743331ca4805edcb
2018-09-11 03:45:04 +03:00
NSString *_text;
NSTextStorage *_textStorage;
NSTextContainer *_textContainer;
NSLayoutManager *_layoutManager;
}
- (instancetype)initWithBridge:(RCTBridge *)bridge
{
if (self = [super init]) {
_bridge = bridge;
_needsUpdateView = YES;
YGNodeSetMeasureFunc(self.yogaNode, RCTBaseTextInputShadowViewMeasure);
YGNodeSetBaselineFunc(self.yogaNode, RCTTextInputShadowViewBaseline);
}
return self;
}
- (BOOL)isYogaLeafNode
{
return YES;
}
- (void)layoutSubviewsWithContext:(RCTLayoutContext)layoutContext
{
// Do nothing.
}
- (void)setLocalData:(NSObject *)localData
{
NSAttributedString *attributedText = (NSAttributedString *)localData;
if ([attributedText isEqualToAttributedString:_localAttributedText]) {
return;
}
_localAttributedText = attributedText;
[self dirtyLayout];
}
- (void)dirtyLayout
{
[super dirtyLayout];
_needsUpdateView = YES;
YGNodeMarkDirty(self.yogaNode);
[self invalidateContentSize];
}
- (void)invalidateContentSize
{
if (!_onContentSizeChange) {
return;
}
CGSize maximumSize = self.layoutMetrics.frame.size;
if (_maximumNumberOfLines == 1) {
maximumSize.width = CGFLOAT_MAX;
} else {
maximumSize.height = CGFLOAT_MAX;
}
CGSize contentSize = [self sizeThatFitsMinimumSize:(CGSize)CGSizeZero maximumSize:maximumSize];
if (CGSizeEqualToSize(_previousContentSize, contentSize)) {
return;
}
_previousContentSize = contentSize;
_onContentSizeChange(@{
@"contentSize": @{
@"height": @(contentSize.height),
@"width": @(contentSize.width),
},
@"target": self.reactTag,
});
}
Fix #18272 TextInput.setNativeProps({text: ''}) to work (#18278) Summary: Fix #18272. Calling textInputRef.setNativeProps({text: ''}) or textInputRef.clear() should clear the text input. - All tests of `yarn run test` are passed - Test with [the sample app](https://github.com/magicien/react-native-textinput-clear). - TextInput.clear() and TextInput.setNativeProps({ text: '***' }) worked - When clear() or setNativeProps() called, onChange/onChangeText wasn't called - Same behavior as react 0.53.0 - When non-string values are given to `setNativeProps({text: ___})`, its behavior is the same as react 0.53.0. - Value Type | Result ---------- | ------------ null | same as empty string '' undefined | nothing changes number | throw error function | throw error object | throw error - When clear() or setNativeProps() called, attributed text keeps the attributes - When `value` prop is set, the text can't be changed - `clear()` doesn't work from the second time - `setNativeProps({text '***'})` doesn't work from the second time - Even when `value` prop is set, you can change the text ![ScreenShot_0.54.0](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/0.54.0_test.gif) - `clear()` works every time - `setNativeProps({text '****'})` works every time ![ScreenShot_Clear_1](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/clear_test_1.gif) ![ScreenShot_Clear_2](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/clear_test_2.gif) - The text keeps the attributes (font family, size, color, text align) ![ScreenShot_Slider](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/attributed_text_test.gif) - If `value` prop is set, the text should not be changed ![ScreenShot_Value](https://raw.githubusercontent.com/magicien/react-native-textinput-clear/master/screenshot/value_test.gif) [IOS] [BUGFIX] [TextInput] - Fix TextInput.clear() and TextInput.setNativeProps({text: ''}) to work Pull Request resolved: https://github.com/facebook/react-native/pull/18278 Reviewed By: shergin Differential Revision: D9692561 Pulled By: hramos fbshipit-source-id: b7ce8f6740fdf666e71d6a85743331ca4805edcb
2018-09-11 03:45:04 +03:00
- (NSString *)text
{
return _text;
}
- (void)setText:(NSString *)text
{
_text = text;
// Clear `_previousAttributedText` to notify the view about the change
// when `text` native prop is set.
_previousAttributedText = nil;
[self dirtyLayout];
}
#pragma mark - RCTUIManagerObserver
- (void)uiManagerWillPerformMounting
{
if (YGNodeIsDirty(self.yogaNode)) {
return;
}
if (!_needsUpdateView) {
return;
}
_needsUpdateView = NO;
UIEdgeInsets borderInsets = self.borderAsInsets;
UIEdgeInsets paddingInsets = self.paddingAsInsets;
RCTTextAttributes *textAttributes = [self.textAttributes copy];
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithAttributedString:[self attributedTextWithBaseTextAttributes:nil]];
// Removing all references to Shadow Views and tags to avoid unnecessary retaining
// and problems with comparing the strings.
[attributedText removeAttribute:RCTBaseTextShadowViewEmbeddedShadowViewAttributeName
range:NSMakeRange(0, attributedText.length)];
[attributedText removeAttribute:RCTTextAttributesTagAttributeName
range:NSMakeRange(0, attributedText.length)];
if (self.text.length) {
NSAttributedString *propertyAttributedText =
[[NSAttributedString alloc] initWithString:self.text
attributes:self.textAttributes.effectiveTextAttributes];
[attributedText insertAttributedString:propertyAttributedText atIndex:0];
}
BOOL isAttributedTextChanged = NO;
if (![_previousAttributedText isEqualToAttributedString:attributedText]) {
// We have to follow `set prop` pattern:
// If the value has not changed, we must not notify the view about the change,
// otherwise we may break local (temporary) state of the text input.
isAttributedTextChanged = YES;
_previousAttributedText = [attributedText copy];
}
NSNumber *tag = self.reactTag;
[_bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
RCTBaseTextInputView *baseTextInputView = (RCTBaseTextInputView *)viewRegistry[tag];
if (!baseTextInputView) {
return;
}
baseTextInputView.textAttributes = textAttributes;
baseTextInputView.reactBorderInsets = borderInsets;
baseTextInputView.reactPaddingInsets = paddingInsets;
if (isAttributedTextChanged) {
// Don't set `attributedText` if length equal to zero, otherwise it would shrink when attributes contain like `lineHeight`.
if (attributedText.length != 0) {
baseTextInputView.attributedText = attributedText;
} else {
baseTextInputView.attributedText = nil;
}
}
}];
}
#pragma mark -
- (NSAttributedString *)measurableAttributedText
{
// Only for the very first render when we don't have `_localAttributedText`,
// we use value directly from the property and/or nested content.
NSAttributedString *attributedText =
_localAttributedText ?: [self attributedTextWithBaseTextAttributes:nil];
if (attributedText.length == 0) {
// It's impossible to measure empty attributed string because all attributes are
// associated with some characters, so no characters means no data.
// Placeholder also can represent the intrinsic size when it is visible.
NSString *text = self.placeholder;
if (!text.length) {
Wrong height when TextInput has an empty string Summary: <!-- Thank you for sending the PR! We appreciate you spending the time to work on these changes. Help us understand your motivation by explaining why you decided to make this change. You can learn more about contributing to React Native here: http://facebook.github.io/react-native/docs/contributing.html Happy contributing! --> The caret/cursor did not appear when the TextInput was empty. Found that the cause was because the frame of the TextInput had an height of 0 Just fill and clear a TextInput and the caret/cursor will always appear there. <!-- Help reviewers and the release process by writing your own release notes **INTERNAL and MINOR tagged notes will not be included in the next version's final release notes.** CATEGORY [----------] TYPE [ CLI ] [-------------] LOCATION [ DOCS ] [ BREAKING ] [-------------] [ GENERAL ] [ BUGFIX ] [-{Component}-] [ INTERNAL ] [ ENHANCEMENT ] [ {File} ] [ IOS ] [ FEATURE ] [ {Directory} ] |-----------| [ ANDROID ] [ MINOR ] [ {Framework} ] - | {Message} | [----------] [-------------] [-------------] |-----------| [CATEGORY] [TYPE] [LOCATION] - MESSAGE EXAMPLES: [IOS] [BREAKING] [FlatList] - Change a thing that breaks other things [ANDROID] [BUGFIX] [TextInput] - Did a thing to TextInput [CLI] [FEATURE] [local-cli/info/info.js] - CLI easier to do things with [DOCS] [BUGFIX] [GettingStarted.md] - Accidentally a thing/word [GENERAL] [ENHANCEMENT] [Yoga] - Added new yoga thing/position [INTERNAL] [FEATURE] [./scripts] - Added thing to script that nobody will see --> [IOS] [BUGFIX] [TextInput] - This was causing the cursor/caret to not appear since the size of the frame had an height of 0. Closes https://github.com/facebook/react-native/pull/18355 Differential Revision: D7319723 Pulled By: shergin fbshipit-source-id: b0249ab5493b6ac310d1898ff20c0bad78cf82c9
2018-03-19 12:10:36 +03:00
// Note: `zero-width space` is insufficient in some cases.
text = @"I";
}
attributedText = [[NSAttributedString alloc] initWithString:text attributes:self.textAttributes.effectiveTextAttributes];
}
return attributedText;
}
- (CGSize)sizeThatFitsMinimumSize:(CGSize)minimumSize maximumSize:(CGSize)maximumSize
{
NSAttributedString *attributedText = [self measurableAttributedText];
if (!_textStorage) {
_textContainer = [NSTextContainer new];
_textContainer.lineFragmentPadding = 0.0; // Note, the default value is 5.
_layoutManager = [NSLayoutManager new];
[_layoutManager addTextContainer:_textContainer];
_textStorage = [NSTextStorage new];
[_textStorage addLayoutManager:_layoutManager];
}
_textContainer.size = maximumSize;
_textContainer.maximumNumberOfLines = _maximumNumberOfLines;
[_textStorage replaceCharactersInRange:(NSRange){0, _textStorage.length}
withAttributedString:attributedText];
[_layoutManager ensureLayoutForTextContainer:_textContainer];
CGSize size = [_layoutManager usedRectForTextContainer:_textContainer].size;
return (CGSize){
MAX(minimumSize.width, MIN(RCTCeilPixelValue(size.width), maximumSize.width)),
MAX(minimumSize.height, MIN(RCTCeilPixelValue(size.height), maximumSize.height))
};
}
- (CGFloat)lastBaselineForSize:(CGSize)size
{
NSAttributedString *attributedText = [self measurableAttributedText];
__block CGFloat maximumDescender = 0.0;
[attributedText enumerateAttribute:NSFontAttributeName
inRange:NSMakeRange(0, attributedText.length)
options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
usingBlock:
^(UIFont *font, NSRange range, __unused BOOL *stop) {
if (maximumDescender > font.descender) {
maximumDescender = font.descender;
}
}
];
return size.height + maximumDescender;
}
static YGSize RCTBaseTextInputShadowViewMeasure(YGNodeRef node, float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode)
{
RCTShadowView *shadowView = (__bridge RCTShadowView *)YGNodeGetContext(node);
CGSize minimumSize = CGSizeMake(0, 0);
CGSize maximumSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
CGSize size = {
RCTCoreGraphicsFloatFromYogaFloat(width),
RCTCoreGraphicsFloatFromYogaFloat(height)
};
switch (widthMode) {
case YGMeasureModeUndefined:
break;
case YGMeasureModeExactly:
minimumSize.width = size.width;
maximumSize.width = size.width;
break;
case YGMeasureModeAtMost:
maximumSize.width = size.width;
break;
}
switch (heightMode) {
case YGMeasureModeUndefined:
break;
case YGMeasureModeExactly:
minimumSize.height = size.height;
maximumSize.height = size.height;
break;
case YGMeasureModeAtMost:
maximumSize.height = size.height;
break;
}
CGSize measuredSize = [shadowView sizeThatFitsMinimumSize:minimumSize maximumSize:maximumSize];
return (YGSize){
RCTYogaFloatFromCoreGraphicsFloat(measuredSize.width),
RCTYogaFloatFromCoreGraphicsFloat(measuredSize.height)
};
}
static float RCTTextInputShadowViewBaseline(YGNodeRef node, const float width, const float height)
{
RCTBaseTextInputShadowView *shadowTextView = (__bridge RCTBaseTextInputShadowView *)YGNodeGetContext(node);
CGSize size = (CGSize){
RCTCoreGraphicsFloatFromYogaFloat(width),
RCTCoreGraphicsFloatFromYogaFloat(height)
};
CGFloat lastBaseline = [shadowTextView lastBaselineForSize:size];
return RCTYogaFloatFromCoreGraphicsFloat(lastBaseline);
}
@end