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 1abff21ef14e..c494a0935fff 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputComponentView.mm @@ -95,6 +95,14 @@ @implementation RCTTextInputComponentView { BOOL _hasInputAccessoryView; CGSize _previousContentSize; + + /* + * The input's paragraph style, with a wrapping line break mode replaced, when the field draws without its line + * height, or nil. TextKit puts a line's extra leading above the glyphs, where CSS splits it equally above and below + * them (https://www.w3.org/TR/CSS2/visudet.html#leading). A single-line field gets the CSS placement by drawing + * without the line height, because `UITextField` centers a line of the font's own height in the field. + */ + NSParagraphStyle *_omittedParagraphStyle; } #pragma mark - UIView overrides @@ -156,9 +164,7 @@ - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection if (UITraitCollection.currentTraitCollection.preferredContentSizeCategory != previousTraitCollection.preferredContentSizeCategory) { - const auto &newTextInputProps = static_cast(*_props); - _backedTextInputView.defaultTextAttributes = - RCTNSTextAttributesFromTextAttributes(newTextInputProps.getEffectiveTextAttributes(RCTFontSizeMultiplier())); + [self _updateDefaultTextAttributesWithProps:static_cast(*_props)]; } } @@ -327,12 +333,11 @@ - (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared & _backedTextInputView.placeholderColor = RCTUIColorFromSharedColor(newTextInputProps.placeholderTextColor); } - if (newTextInputProps.textAttributes != oldTextInputProps.textAttributes) { - NSMutableDictionary *defaultAttributes = - RCTNSTextAttributesFromTextAttributes(newTextInputProps.getEffectiveTextAttributes(RCTFontSizeMultiplier())); - defaultAttributes[RCTAttributedStringEventEmitterKey] = - _backedTextInputView.defaultTextAttributes[RCTAttributedStringEventEmitterKey]; - _backedTextInputView.defaultTextAttributes = defaultAttributes; + // Recompute the attributes when `multiline` changes too: only a single-line field omits the line height and + // replaces a wrapping line break mode. + if (newTextInputProps.textAttributes != oldTextInputProps.textAttributes || + newTextInputProps.multiline != oldTextInputProps.multiline) { + [self _updateDefaultTextAttributesWithProps:newTextInputProps]; } if (newTextInputProps.selectionColor != oldTextInputProps.selectionColor) { @@ -820,15 +825,23 @@ - (void)_updateState if (!_state) { return; } - NSAttributedString *attributedString = _backedTextInputView.attributedText; auto data = _state->getData(); - _lastStringStateWasUpdatedWith = attributedString; - data.attributedStringBox = RCTAttributedStringBoxFromNSAttributedString(attributedString); + _lastStringStateWasUpdatedWith = _backedTextInputView.attributedText; + data.attributedStringBox = RCTAttributedStringBoxFromNSAttributedString([self _attributedStringForState]); _mostRecentEventCount += _comingFromJS ? 0 : 1; data.mostRecentEventCount = _mostRecentEventCount; _state->updateState(std::move(data)); } +// Returns the field's text with the paragraph styles the field draws without, which is the form the state holds. +- (NSAttributedString *)_attributedStringForState +{ + NSAttributedString *attributedString = _backedTextInputView.attributedText; + return _omittedParagraphStyle != nil + ? RCTAttributedStringByRestoringLineHeight(attributedString, _omittedParagraphStyle) + : attributedString; +} + - (AttributedString::Range)_selectionRange { UITextRange *selectedTextRange = _backedTextInputView.selectedTextRange; @@ -860,19 +873,50 @@ - (void)_restoreTextSelectionAndIgnoreCaretChange:(BOOL)ignore [_backedTextInputView setSelectedTextRange:range notifyDelegate:YES]; } +// Sets the field's default text attributes from `props`, and `_omittedParagraphStyle` with them. +- (void)_updateDefaultTextAttributesWithProps:(const TextInputProps &)props +{ + NSMutableDictionary *attributes = + RCTNSTextAttributesFromTextAttributes(props.getEffectiveTextAttributes(RCTFontSizeMultiplier())); + NSParagraphStyle *paragraphStyle = attributes[NSParagraphStyleAttributeName]; + if (!props.multiline && paragraphStyle != nil) { + paragraphStyle = RCTSingleLineParagraphStyle(paragraphStyle); + attributes[NSParagraphStyleAttributeName] = paragraphStyle; + } + // Record the style after that replacement: `_setAttributedString` compares the restored text with a state's + // text whose styles are replaced too. + _omittedParagraphStyle = !props.multiline && paragraphStyle.maximumLineHeight > 0 ? [paragraphStyle copy] : nil; + if (_omittedParagraphStyle != nil) { + attributes[NSParagraphStyleAttributeName] = RCTParagraphStyleByOmittingLineHeight(paragraphStyle); + } + attributes[RCTAttributedStringEventEmitterKey] = + _backedTextInputView.defaultTextAttributes[RCTAttributedStringEventEmitterKey]; + _backedTextInputView.defaultTextAttributes = attributes; +} + - (void)_setAttributedString:(NSAttributedString *)attributedString { - if ([self _textOf:attributedString equals:_backedTextInputView.attributedText]) { + BOOL isMultiline = _props ? static_cast(*_props).multiline + : [_backedTextInputView isKindOfClass:[UITextView class]]; + // Compare with the single-line paragraph styles the field's text has. Writing them back to the state doesn't + // change layout: a single-line input is measured at unlimited width, where wrapping and truncating agree. + if (!isMultiline) { + attributedString = RCTAttributedStringWithSingleLineParagraphStyles(attributedString); + } + // Restore the paragraph styles the field draws without, so that its text can match the state's. + NSAttributedString *oldAttributedString = [self _attributedStringForState]; + if ([self _textOf:attributedString equals:oldAttributedString]) { return; } + if (_omittedParagraphStyle != nil) { + attributedString = RCTAttributedStringByOmittingLineHeight(attributedString, _omittedParagraphStyle); + } UITextRange *selectedRange = _backedTextInputView.selectedTextRange; NSInteger oldTextLength = _backedTextInputView.attributedText.string.length; _backedTextInputView.attributedText = attributedString; // A single-line input that is not being edited has no cursor to keep: UIKit places one when editing begins. // Restoring it anyway makes UIKit scroll the field editor to it when the text doesn't fit, and the editor keeps // that offset after the text fits again, so text typed later in this view (also after recycling) is drawn too high. - BOOL isMultiline = _props ? static_cast(*_props).multiline - : [_backedTextInputView isKindOfClass:[UITextView class]]; if (isMultiline || _backedTextInputView.isFirstResponder) { // Updating the UITextView attributedText, for example changing the lineHeight, the color or adding // a new paragraph with \n, causes the cursor to move to the end of the Text and scroll. diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputUtils.h b/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputUtils.h index 90a2816bf2ad..18b282895fea 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputUtils.h +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputUtils.h @@ -18,6 +18,41 @@ void RCTCopyBackedTextInput( UIView *fromTextInput, UIView *toTextInput); +/* + * Returns `paragraphStyle` with `NSLineBreakByTruncatingTail` in place of a wrapping line break mode, as + * `UITextField`'s own default paragraph style has. A text field that is not being edited lays out its text as the + * paragraph style says, so a wrapping mode draws a second line. + */ +NSParagraphStyle *RCTSingleLineParagraphStyle(NSParagraphStyle *paragraphStyle); + +/* + * Returns `attributedString` with each paragraph style replaced as `RCTSingleLineParagraphStyle` does. + */ +NSAttributedString *RCTAttributedStringWithSingleLineParagraphStyles(NSAttributedString *attributedString); + +/* + * Returns `paragraphStyle` with no minimum or maximum line height and the rest of the style unchanged. + */ +NSParagraphStyle *RCTParagraphStyleByOmittingLineHeight(NSParagraphStyle *paragraphStyle); + +/* + * Returns `attributedString` with each paragraph style that has a line height replaced as + * `RCTParagraphStyleByOmittingLineHeight` does. A private attribute records the replaced style of each range + * where it is not `inputParagraphStyle`, the input's own, so that the other ranges follow the input when its + * style changes. + */ +NSAttributedString *RCTAttributedStringByOmittingLineHeight( + NSAttributedString *attributedString, + NSParagraphStyle *inputParagraphStyle); + +/* + * Reverses `RCTAttributedStringByOmittingLineHeight`: each range gets back the paragraph style recorded for it. A + * range with no record, such as the input's own text and text typed into the field, gets `inputParagraphStyle`. + */ +NSAttributedString *RCTAttributedStringByRestoringLineHeight( + NSAttributedString *attributedString, + NSParagraphStyle *inputParagraphStyle); + UITextAutocorrectionType RCTUITextAutocorrectionTypeFromOptionalBool(std::optional autoCorrect); UITextAutocapitalizationType RCTUITextAutocapitalizationTypeFromAutocapitalizationType( diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputUtils.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputUtils.mm index e10e01d20430..3f638bfeb42d 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputUtils.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputUtils.mm @@ -53,6 +53,87 @@ void RCTCopyBackedTextInput( [toTextInput setSelectedTextRange:fromTextInput.selectedTextRange notifyDelegate:NO]; } +NSParagraphStyle *RCTSingleLineParagraphStyle(NSParagraphStyle *paragraphStyle) +{ + if (paragraphStyle.lineBreakMode != NSLineBreakByWordWrapping && + paragraphStyle.lineBreakMode != NSLineBreakByCharWrapping) { + return paragraphStyle; + } + NSMutableParagraphStyle *copy = [paragraphStyle mutableCopy]; + copy.lineBreakMode = NSLineBreakByTruncatingTail; + return copy; +} + +NSAttributedString *RCTAttributedStringWithSingleLineParagraphStyles(NSAttributedString *attributedString) +{ + NSMutableAttributedString *copy = [attributedString mutableCopy]; + [attributedString enumerateAttribute:NSParagraphStyleAttributeName + inRange:NSMakeRange(0, attributedString.length) + options:0 + usingBlock:^(NSParagraphStyle *paragraphStyle, NSRange range, BOOL *stop) { + if (paragraphStyle != nil) { + [copy addAttribute:NSParagraphStyleAttributeName + value:RCTSingleLineParagraphStyle(paragraphStyle) + range:range]; + } + }]; + return copy; +} + +static const NSAttributedStringKey RCTOmittedParagraphStyleAttributeName = @"RCTOmittedParagraphStyle"; + +NSParagraphStyle *RCTParagraphStyleByOmittingLineHeight(NSParagraphStyle *paragraphStyle) +{ + NSMutableParagraphStyle *copy = [paragraphStyle mutableCopy]; + copy.minimumLineHeight = 0; + copy.maximumLineHeight = 0; + return copy; +} + +NSAttributedString *RCTAttributedStringByOmittingLineHeight( + NSAttributedString *attributedString, + NSParagraphStyle *inputParagraphStyle) +{ + NSMutableAttributedString *copy = [attributedString mutableCopy]; + [attributedString enumerateAttribute:NSParagraphStyleAttributeName + inRange:NSMakeRange(0, attributedString.length) + options:0 + usingBlock:^(NSParagraphStyle *paragraphStyle, NSRange range, BOOL *stop) { + // Leave a style with no line height as it is: a record of it would keep the + // input's line height from the range on restore. + if (paragraphStyle.maximumLineHeight <= 0) { + return; + } + [copy addAttribute:NSParagraphStyleAttributeName + value:RCTParagraphStyleByOmittingLineHeight(paragraphStyle) + range:range]; + if (![paragraphStyle isEqual:inputParagraphStyle]) { + [copy addAttribute:RCTOmittedParagraphStyleAttributeName + value:paragraphStyle + range:range]; + } + }]; + return copy; +} + +NSAttributedString *RCTAttributedStringByRestoringLineHeight( + NSAttributedString *attributedString, + NSParagraphStyle *inputParagraphStyle) +{ + NSRange fullRange = NSMakeRange(0, attributedString.length); + NSMutableAttributedString *copy = [attributedString mutableCopy]; + [copy removeAttribute:RCTOmittedParagraphStyleAttributeName range:fullRange]; + [attributedString enumerateAttribute:RCTOmittedParagraphStyleAttributeName + inRange:fullRange + options:0 + usingBlock:^(NSParagraphStyle *omittedParagraphStyle, NSRange range, BOOL *stop) { + [copy addAttribute:NSParagraphStyleAttributeName + value:omittedParagraphStyle ?: inputParagraphStyle + range:range]; + }]; + return copy; +} + UITextAutocorrectionType RCTUITextAutocorrectionTypeFromOptionalBool(std::optional autoCorrect) { return autoCorrect.has_value() ? (*autoCorrect ? UITextAutocorrectionTypeYes : UITextAutocorrectionTypeNo) diff --git a/packages/react-native/React/Tests/Text/RCTTextInputComponentViewTests.mm b/packages/react-native/React/Tests/Text/RCTTextInputComponentViewTests.mm index 396191cb9ebb..7aae99312bb6 100644 --- a/packages/react-native/React/Tests/Text/RCTTextInputComponentViewTests.mm +++ b/packages/react-native/React/Tests/Text/RCTTextInputComponentViewTests.mm @@ -5,10 +5,14 @@ * LICENSE file in the root directory of this source tree. */ +#import +#import #import #import #import #import +#import +#import using namespace facebook::react; @@ -21,6 +25,19 @@ return props; } +// Props with a 16 pt font and the given line height, or none when it is NaN. +static std::shared_ptr propsWithLineHeight(bool multiline, Float lineHeight = 40) +{ + auto props = std::make_shared(); + props->multiline = multiline; + // A unit test has no application to read the content size category from, so `RCTFontSizeMultiplier()` is 0 here + // and would scale the line height to 0. Without font scaling the field gets the line height as written. + props->textAttributes.allowFontScaling = false; + props->textAttributes.fontSize = 16; + props->textAttributes.lineHeight = lineHeight; + return props; +} + static UITextField *backedTextField(RCTTextInputComponentView *view) { return [view valueForKey:@"_backedTextInputView"]; @@ -31,11 +48,458 @@ return backedTextField(view).defaultTextAttributes[NSParagraphStyleAttributeName]; } +struct TextRun { + std::string text; + Float lineHeight; + std::optional alignment{}; +}; + +// A state holding the text the shadow node builds from the React tree: each run has the input's attributes, its +// own line height and, when the run names one, its own alignment, as a nested `` does. +static TextInputShadowNode::ConcreteState::Shared +stateWithRuns(const TextInputProps &props, std::vector runs, int64_t eventCount) +{ + AttributedString attributedString; + for (const auto &run : runs) { + auto textAttributes = props.getEffectiveTextAttributes(1); + textAttributes.lineHeight = run.lineHeight; + if (run.alignment.has_value()) { + textAttributes.alignment = run.alignment; + } + attributedString.appendFragment({.string = run.text, .textAttributes = textAttributes}); + } + return std::make_shared( + std::make_shared( + AttributedStringBox{attributedString}, attributedString, ParagraphAttributes{}, eventCount), + ShadowNodeFamily::Weak{}); +} + +// Inserts `text` at `offset` as the keyboard does. A unit test has no application to deliver the field's +// editing-changed action, so this reports the change to the component view itself. +static void typeText(RCTTextInputComponentView *view, NSString *text, NSInteger offset) +{ + UITextField *textField = backedTextField(view); + UITextPosition *position = [textField positionFromPosition:textField.beginningOfDocument offset:offset]; + textField.selectedTextRange = [textField textRangeFromPosition:position toPosition:position]; + [textField insertText:text]; + [(id)view textInputDidChange]; +} + +// The text the view writes to its state after a change. +static NSAttributedString *attributedStringForState(RCTTextInputComponentView *view) +{ + return [view valueForKey:@"_attributedStringForState"]; +} + +static CGFloat maximumLineHeightAtIndex(NSAttributedString *attributedString, NSUInteger index) +{ + NSParagraphStyle *paragraphStyle = [attributedString attribute:NSParagraphStyleAttributeName + atIndex:index + effectiveRange:NULL]; + return paragraphStyle.maximumLineHeight; +} + +// The line height a single-line field recorded for the range at `index` when it left it out of the drawn text. +static NSNumber *omittedLineHeightRecordAtIndex(NSAttributedString *attributedString, NSUInteger index) +{ + NSParagraphStyle *record = [attributedString attribute:@"RCTOmittedParagraphStyle" atIndex:index effectiveRange:NULL]; + return record != nil ? @(record.maximumLineHeight) : nil; +} + +static NSUInteger eventCount(RCTTextInputComponentView *view) +{ + return [[view valueForKey:@"_mostRecentEventCount"] unsignedIntegerValue]; +} + +static NSInteger caretOffset(UITextField *textField) +{ + return [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start]; +} + +// Returns how far below the vertical center of a field of the given height the center of its text is drawn. +static CGFloat textCenterOffset(Float lineHeight, CGFloat height) +{ + auto props = propsWithLineHeight(false, lineHeight); + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + [view updateProps:props oldProps:TextInputShadowNode::defaultSharedProps()]; + LayoutMetrics layoutMetrics{.frame = {.origin = {0, 0}, .size = {100, static_cast(height)}}}; + [view updateLayoutMetrics:layoutMetrics oldLayoutMetrics:{}]; + [view updateState:stateWithRuns(*props, {{"\u00c1gjpqy", lineHeight}}, 0) oldState:nullptr]; + [view layoutIfNeeded]; + + // Text taller than its field is drawn outside it, so the bitmap has a margin above and below the field + const CGFloat margin = 40; + const size_t scale = 2; + const size_t width = 100 * scale; + const size_t rows = static_cast(height + 2 * margin) * scale; + std::vector pixels(width * rows, 0xff); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); + CGContextRef context = + CGBitmapContextCreate(pixels.data(), width, rows, 8, width, colorSpace, (CGBitmapInfo)kCGImageAlphaNone); + CGColorSpaceRelease(colorSpace); + CGContextTranslateCTM(context, 0, rows); + CGContextScaleCTM(context, scale, -1.0 * scale); + CGContextTranslateCTM(context, 0, margin); + [view.layer renderInContext:context]; + CGContextRelease(context); + + NSInteger firstRow = -1; + NSInteger lastRow = -1; + for (size_t row = 0; row < rows; row++) { + for (size_t column = 0; column < width; column++) { + if (pixels[row * width + column] < 0x80) { + firstRow = firstRow < 0 ? row : firstRow; + lastRow = row; + break; + } + } + } + if (firstRow < 0) { + return NAN; + } + return (firstRow + lastRow + 1) / 2.0 / scale - (margin + height / 2); +} + +static const std::string kWideText = "one two three four five six seven eight"; + +// Props with a 16 pt font, no line height and, unless `alignment` is empty, a paragraph style that aligns the text. +static std::shared_ptr propsWithAlignment( + bool multiline, + std::optional alignment = TextAlignment::Right) +{ + auto props = std::make_shared(*propsWithLineHeight(multiline, NAN)); + props->textAttributes.alignment = alignment; + return props; +} + +// Returns the number of lines of text a 100 pt by 60 pt input draws, which is tall enough for three lines of its +// font. +static NSUInteger linesDrawn( + std::shared_ptr props, + TextInputShadowNode::ConcreteState::Shared state) +{ + const size_t width = 100; + const size_t height = 60; + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + [view updateProps:props oldProps:TextInputShadowNode::defaultSharedProps()]; + LayoutMetrics layoutMetrics{.frame = {.origin = {0, 0}, .size = {width, height}}}; + [view updateLayoutMetrics:layoutMetrics oldLayoutMetrics:{}]; + [view updateState:state oldState:nullptr]; + [view layoutIfNeeded]; + + std::vector pixels(width * height, 0xff); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); + CGContextRef context = + CGBitmapContextCreate(pixels.data(), width, height, 8, width, colorSpace, (CGBitmapInfo)kCGImageAlphaNone); + CGColorSpaceRelease(colorSpace); + CGContextTranslateCTM(context, 0, height); + CGContextScaleCTM(context, 1, -1); + [view.layer renderInContext:context]; + CGContextRelease(context); + + // Lines of text are separated by rows with no ink + NSUInteger lines = 0; + BOOL wasInk = NO; + for (size_t row = 0; row < height; row++) { + BOOL isInk = NO; + for (size_t column = 0; column < width && !isInk; column++) { + isInk = pixels[row * width + column] < 0xc0; + } + lines += isInk && !wasInk ? 1 : 0; + wasInk = isInk; + } + return lines; +} + +// Counts how many times a text field's attributed text is set. +@interface RCTAttributedTextSetCounter : NSObject +@property (nonatomic, readonly) NSUInteger count; +- (instancetype)initWithTextField:(UITextField *)textField; +@end + +@implementation RCTAttributedTextSetCounter { + UITextField *_textField; +} + +- (instancetype)initWithTextField:(UITextField *)textField +{ + if (self = [super init]) { + _textField = textField; + [_textField addObserver:self forKeyPath:@"attributedText" options:0 context:nullptr]; + } + return self; +} + +- (void)dealloc +{ + [_textField removeObserver:self forKeyPath:@"attributedText"]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(NSDictionary *)change + context:(void *)context +{ + _count++; +} + +@end + @interface RCTTextInputComponentViewTests : XCTestCase @end @implementation RCTTextInputComponentViewTests +- (void)testSingleLineInputDrawsWithoutLineHeight +{ + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + [view updateProps:propsWithLineHeight(false) oldProps:TextInputShadowNode::defaultSharedProps()]; + NSParagraphStyle *paragraphStyle = defaultParagraphStyle(view); + + XCTAssertNotNil(paragraphStyle); + XCTAssertEqual(paragraphStyle.minimumLineHeight, 0); + XCTAssertEqual(paragraphStyle.maximumLineHeight, 0); + // The state gets the line height back, because layout measures the field from it. + XCTAssertEqual([(NSParagraphStyle *)[view valueForKey:@"_omittedParagraphStyle"] maximumLineHeight], 40); +} + +- (void)testMultilineInputDrawsWithLineHeight +{ + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + [view updateProps:propsWithLineHeight(true) oldProps:TextInputShadowNode::defaultSharedProps()]; + + XCTAssertEqual(defaultParagraphStyle(view).minimumLineHeight, 40); + XCTAssertEqual(defaultParagraphStyle(view).maximumLineHeight, 40); +} + +- (void)testInputThatBecomesMultilineDrawsWithLineHeight +{ + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + auto singleLineProps = propsWithLineHeight(false); + [view updateProps:singleLineProps oldProps:TextInputShadowNode::defaultSharedProps()]; + [view updateProps:propsWithLineHeight(true) oldProps:singleLineProps]; + + XCTAssertEqual(defaultParagraphStyle(view).minimumLineHeight, 40); + XCTAssertEqual(defaultParagraphStyle(view).maximumLineHeight, 40); +} + +- (void)testInputWithTextThatBecomesMultilineKeepsNoOmittedLineHeight +{ + auto singleLineProps = propsWithLineHeight(false, 24); + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + [view updateProps:singleLineProps oldProps:TextInputShadowNode::defaultSharedProps()]; + auto state = stateWithRuns(*singleLineProps, {{"ab", 24}, {"cd", 40}}, 0); + [view updateState:state oldState:nullptr]; + XCTAssertEqualObjects(omittedLineHeightRecordAtIndex(backedTextField(view).attributedText, 2), @40); + + auto multilineProps = propsWithLineHeight(true, 24); + [view updateProps:multilineProps oldProps:singleLineProps]; + + // The new view gets the text without its attributes, so no record reaches a view that omits nothing, and the + // text for the state is the view's text as it is. + UITextView *textView = [view valueForKey:@"_backedTextInputView"]; + XCTAssertTrue([textView isKindOfClass:[UITextView class]]); + XCTAssertEqualObjects(textView.text, @"abcd"); + XCTAssertNil(omittedLineHeightRecordAtIndex(textView.attributedText, 0)); + XCTAssertNil(omittedLineHeightRecordAtIndex(textView.attributedText, 2)); + XCTAssertEqualObjects(attributedStringForState(view), textView.attributedText); + + // A state gives the text its attributes again, with the line height that spaces the lines + [view updateState:stateWithRuns(*multilineProps, {{"ab", 24}, {"cd", 40}}, 0) oldState:state]; + XCTAssertEqual(maximumLineHeightAtIndex(textView.attributedText, 0), 24); + XCTAssertNil(omittedLineHeightRecordAtIndex(textView.attributedText, 2)); + XCTAssertEqualObjects(attributedStringForState(view), textView.attributedText); + // Neither step reports a change of the text + XCTAssertEqual(eventCount(view), 0); +} + +- (void)testInputWithTextThatBecomesSingleLineDrawsWithoutLineHeight +{ + auto multilineProps = propsWithLineHeight(true, 24); + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + [view updateProps:multilineProps oldProps:TextInputShadowNode::defaultSharedProps()]; + auto state = stateWithRuns(*multilineProps, {{"ab", 24}, {"cd", 40}}, 0); + [view updateState:state oldState:nullptr]; + + auto singleLineProps = propsWithLineHeight(false, 24); + [view updateProps:singleLineProps oldProps:multilineProps]; + + // The new field gets the text without its attributes and gives it the default ones, so all of it is the + // input's own text until a state names the runs again. + UITextField *textField = backedTextField(view); + XCTAssertTrue([textField isKindOfClass:[UITextField class]]); + XCTAssertEqualObjects(textField.text, @"abcd"); + XCTAssertEqual(maximumLineHeightAtIndex(textField.attributedText, 0), 0); + XCTAssertEqual(maximumLineHeightAtIndex(textField.attributedText, 2), 0); + XCTAssertEqual(maximumLineHeightAtIndex(attributedStringForState(view), 0), 24); + XCTAssertEqual(maximumLineHeightAtIndex(attributedStringForState(view), 2), 24); + + [view updateState:stateWithRuns(*singleLineProps, {{"ab", 24}, {"cd", 40}}, 0) oldState:state]; + XCTAssertEqual(maximumLineHeightAtIndex(textField.attributedText, 0), 0); + XCTAssertEqual(maximumLineHeightAtIndex(textField.attributedText, 2), 0); + XCTAssertNil(omittedLineHeightRecordAtIndex(textField.attributedText, 0)); + XCTAssertEqualObjects(omittedLineHeightRecordAtIndex(textField.attributedText, 2), @40); + XCTAssertEqual(maximumLineHeightAtIndex(attributedStringForState(view), 0), 24); + XCTAssertEqual(maximumLineHeightAtIndex(attributedStringForState(view), 2), 40); + XCTAssertEqual(eventCount(view), 0); +} + +- (void)testSingleLineInputCentersTextOnTheFieldAtAnyLineHeight +{ + // A 16 pt system font has a line about 19 pt tall. A field with no line height is that tall, and one with a + // line height is as tall as the line height. + CGFloat withoutLineHeight = textCenterOffset(NAN, 19); + XCTAssertFalse(isnan(withoutLineHeight)); + + XCTAssertEqualWithAccuracy(textCenterOffset(40, 40), withoutLineHeight, 1); + // A line height below the font's line: the text is not squeezed toward the top of the field + XCTAssertEqualWithAccuracy(textCenterOffset(10, 10), withoutLineHeight, 1); +} + +- (void)testStateEchoingTypedTextLeavesTheFieldAlone +{ + auto props = propsWithLineHeight(false); + RCTTextInputComponentView *view = [self focusedViewWithProps:props]; + UITextField *textField = backedTextField(view); + auto emptyState = stateWithRuns(*props, {}, 0); + [view updateState:emptyState oldState:nullptr]; + RCTAttributedTextSetCounter *counter = [[RCTAttributedTextSetCounter alloc] initWithTextField:textField]; + + // A controlled input answers each change with a state built from its `value`, which has the line height. + // Text typed into an empty field has no record of the line height it is drawn without. + typeText(view, @"ab", 0); + auto firstEcho = stateWithRuns(*props, {{"ab", 40}}, 1); + [view updateState:firstEcho oldState:emptyState]; + typeText(view, @"X", 1); + auto secondEcho = stateWithRuns(*props, {{"aXb", 40}}, 2); + [view updateState:secondEcho oldState:firstEcho]; + + XCTAssertEqual(counter.count, 0); + XCTAssertEqualObjects(textField.text, @"aXb"); + XCTAssertEqual(caretOffset(textField), 2); + + // A state with other text does replace the field's text, so the count above is of states that were compared + [view updateState:stateWithRuns(*props, {{"aXbc", 40}}, 2) oldState:secondEcho]; + XCTAssertEqual(counter.count, 1); + XCTAssertEqualObjects(textField.text, @"aXbc"); +} + +- (void)testStateWrittenAfterTypingHasTheLineHeightAndLeavesTheFieldAlone +{ + auto props = propsWithLineHeight(false); + RCTTextInputComponentView *view = [self focusedViewWithProps:props]; + UITextField *textField = backedTextField(view); + auto emptyState = stateWithRuns(*props, {}, 0); + [view updateState:emptyState oldState:nullptr]; + RCTAttributedTextSetCounter *counter = [[RCTAttributedTextSetCounter alloc] initWithTextField:textField]; + + typeText(view, @"ab", 0); + NSAttributedString *written = attributedStringForState(view); + + // Layout measures the field from this text + XCTAssertEqualObjects(written.string, @"ab"); + XCTAssertEqual(maximumLineHeightAtIndex(written, 0), 40); + XCTAssertEqual(maximumLineHeightAtIndex(textField.attributedText, 0), 0); + + // An uncontrolled input gets back the state it wrote + auto writtenState = std::make_shared( + std::make_shared( + RCTAttributedStringBoxFromNSAttributedString(written), AttributedString{}, ParagraphAttributes{}, 1), + ShadowNodeFamily::Weak{}); + [view updateState:writtenState oldState:emptyState]; + XCTAssertEqual(counter.count, 0); + XCTAssertEqual(caretOffset(textField), 2); +} + +- (void)testStateEchoingTextTypedIntoNestedRunLeavesTheFieldAlone +{ + auto props = propsWithLineHeight(false, 24); + RCTTextInputComponentView *view = [self focusedViewWithProps:props]; + UITextField *textField = backedTextField(view); + // The last run has the input's line height and its own alignment, so it differs from the input outside its + // line height + auto initialState = stateWithRuns(*props, {{"ab", 24}, {"cd", 40}, {"ef", 24, TextAlignment::Right}}, 0); + [view updateState:initialState oldState:nullptr]; + RCTAttributedTextSetCounter *counter = [[RCTAttributedTextSetCounter alloc] initWithTextField:textField]; + + // Typed inside the nested run, whose line height differs from the input's. The caret is placed in code, which + // keeps the run's attributes for the typed text; a tap that moves the caret does not. + typeText(view, @"X", 3); + auto echo = stateWithRuns(*props, {{"ab", 24}, {"cXd", 40}, {"ef", 24, TextAlignment::Right}}, 1); + [view updateState:echo oldState:initialState]; + + XCTAssertEqual(counter.count, 0); + XCTAssertEqualObjects(textField.text, @"abcXdef"); + XCTAssertEqual(caretOffset(textField), 4); + + // The same text with the input's line height on the typed character is different text + [view updateState:stateWithRuns( + *props, {{"ab", 24}, {"c", 40}, {"X", 24}, {"d", 40}, {"ef", 24, TextAlignment::Right}}, 1) + oldState:echo]; + XCTAssertEqual(counter.count, 1); +} + +- (void)testChangingLineHeightChangesItForTheInputsOwnTextOnly +{ + auto props = propsWithLineHeight(false, 24); + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + [view updateProps:props oldProps:TextInputShadowNode::defaultSharedProps()]; + [view updateState:stateWithRuns(*props, {{"ab", 24}, {"cd", 40}}, 0) oldState:nullptr]; + + [view updateProps:propsWithLineHeight(false, 30) oldProps:props]; + + NSAttributedString *written = attributedStringForState(view); + XCTAssertEqual(maximumLineHeightAtIndex(written, 0), 30); + XCTAssertEqual(maximumLineHeightAtIndex(written, 2), 40); +} + +- (void)testSingleLineInputWithParagraphStyleDrawsWideTextOnOneLine +{ + auto props = propsWithAlignment(false); + XCTAssertEqual(linesDrawn(props, stateWithRuns(*props, {{kWideText, NAN}}, 0)), 1); + + // The paragraph style of a nested ``, in an input that has none of its own + auto plainProps = propsWithAlignment(false, std::nullopt); + XCTAssertEqual(linesDrawn(plainProps, stateWithRuns(*plainProps, {{kWideText, NAN, TextAlignment::Right}}, 0)), 1); + + // With a line height, which the field draws without: a wrapping style would draw more lines of the font + auto lineHeightProps = propsWithLineHeight(false, 40); + XCTAssertEqual(linesDrawn(lineHeightProps, stateWithRuns(*lineHeightProps, {{kWideText, 40}}, 0)), 1); + + // A multi-line input wraps, which also shows that a second line would be counted + auto multilineProps = propsWithAlignment(true); + XCTAssertEqual(linesDrawn(multilineProps, stateWithRuns(*multilineProps, {{kWideText, NAN}}, 0)), 3); +} + +- (void)testOnlySingleLineInputReplacesWrappingLineBreakMode +{ + auto singleLineProps = propsWithAlignment(false); + auto multilineProps = propsWithAlignment(true); + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + + [view updateProps:singleLineProps oldProps:TextInputShadowNode::defaultSharedProps()]; + XCTAssertEqual(defaultParagraphStyle(view).lineBreakMode, NSLineBreakByTruncatingTail); + // The placeholder is drawn with the default text attributes + UITextField *textField = backedTextField(view); + textField.placeholder = @"placeholder"; + NSParagraphStyle *placeholderStyle = [textField.attributedPlaceholder attribute:NSParagraphStyleAttributeName + atIndex:0 + effectiveRange:NULL]; + XCTAssertEqual(placeholderStyle.lineBreakMode, NSLineBreakByTruncatingTail); + XCTAssertEqual(placeholderStyle.alignment, NSTextAlignmentRight); + + [view updateProps:multilineProps oldProps:singleLineProps]; + XCTAssertEqual(defaultParagraphStyle(view).lineBreakMode, NSLineBreakByWordWrapping); + + [view updateProps:singleLineProps oldProps:multilineProps]; + XCTAssertEqual(defaultParagraphStyle(view).lineBreakMode, NSLineBreakByTruncatingTail); + + // A change of the content size category sets the attributes again + [view traitCollectionDidChange:[UITraitCollection traitCollectionWithPreferredContentSizeCategory: + UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]]; + XCTAssertEqual(defaultParagraphStyle(view).lineBreakMode, NSLineBreakByTruncatingTail); +} + - (void)testChangeOfLineBreakModeAloneSetsDefaultTextAttributes { RCTTextInputComponentView *view = [RCTTextInputComponentView new]; @@ -53,4 +517,63 @@ - (void)testChangeOfLineBreakModeAloneSetsDefaultTextAttributes XCTAssertNil(defaultParagraphStyle(view)); } +- (void)testStateRepeatingTypedTextLeavesTheFieldAlone +{ + auto props = propsWithAlignment(false); + RCTTextInputComponentView *view = [self focusedViewWithProps:props]; + UITextField *textField = backedTextField(view); + // A controlled input answers a change with a state built from the React tree, whose paragraph style wraps + auto emptyState = stateWithRuns(*props, {}, 0); + [view updateState:emptyState oldState:nullptr]; + typeText(view, @"ab", 0); + auto firstState = stateWithRuns(*props, {{"ab", NAN}}, 1); + [view updateState:firstState oldState:emptyState]; + + // Count from here: the text typed into the empty field has no paragraph style in this test, so the first state + // sets the field's text once, whether or not the styles are replaced + RCTAttributedTextSetCounter *counter = [[RCTAttributedTextSetCounter alloc] initWithTextField:textField]; + typeText(view, @"c", 2); + auto controlledState = stateWithRuns(*props, {{"abc", NAN}}, 2); + [view updateState:controlledState oldState:firstState]; + XCTAssertEqual(counter.count, 0); + + // An uncontrolled input gets back the text the view wrote to the state, which is the field's own + auto writtenState = std::make_shared( + std::make_shared( + RCTAttributedStringBoxFromNSAttributedString(textField.attributedText), + AttributedString{}, + ParagraphAttributes{}, + 2), + ShadowNodeFamily::Weak{}); + [view updateState:writtenState oldState:controlledState]; + XCTAssertEqual(counter.count, 0); + XCTAssertEqualObjects(textField.text, @"abc"); + XCTAssertEqual(caretOffset(textField), 3); + + // A state with other text does replace the field's text, so the counts above are of states that were compared + [view updateState:stateWithRuns(*props, {{"abcd", NAN}}, 2) oldState:writtenState]; + XCTAssertEqual(counter.count, 1); + XCTAssertEqualObjects(textField.text, @"abcd"); +} + +// Returns a single-line input that is being edited, in a window that the test removes as it ends. +- (RCTTextInputComponentView *)focusedViewWithProps:(std::shared_ptr)props +{ + RCTTextInputComponentView *view = [RCTTextInputComponentView new]; + [view updateProps:props oldProps:TextInputShadowNode::defaultSharedProps()]; + LayoutMetrics layoutMetrics{.frame = {.origin = {0, 0}, .size = {200, 40}}}; + [view updateLayoutMetrics:layoutMetrics oldLayoutMetrics:{}]; + UIWindow *window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 200, 40)]; + [window addSubview:view]; + window.hidden = NO; + UITextField *textField = backedTextField(view); + XCTAssertTrue([textField becomeFirstResponder]); + [self addTeardownBlock:^{ + [textField resignFirstResponder]; + [view removeFromSuperview]; + window.hidden = YES; + }]; + return view; +} + @end diff --git a/packages/react-native/React/Tests/Text/RCTTextInputUtilsTest.mm b/packages/react-native/React/Tests/Text/RCTTextInputUtilsTest.mm index 0adb9424c4af..350ecb50715e 100644 --- a/packages/react-native/React/Tests/Text/RCTTextInputUtilsTest.mm +++ b/packages/react-native/React/Tests/Text/RCTTextInputUtilsTest.mm @@ -10,6 +10,24 @@ #import #import +static NSParagraphStyle *paragraphStyleWithLineHeight(CGFloat lineHeight) +{ + NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new]; + paragraphStyle.minimumLineHeight = lineHeight; + paragraphStyle.maximumLineHeight = lineHeight; + return paragraphStyle; +} + +static NSDictionary *attributesWithLineHeight(CGFloat lineHeight) +{ + return @{NSParagraphStyleAttributeName : paragraphStyleWithLineHeight(lineHeight)}; +} + +static NSParagraphStyle *paragraphStyleAtIndex(NSAttributedString *attributedString, NSUInteger index) +{ + return [attributedString attribute:NSParagraphStyleAttributeName atIndex:index effectiveRange:NULL]; +} + @interface RCTTextInputUtilsTest : XCTestCase @end @@ -37,4 +55,111 @@ - (void)testCopyBackedTextInputPreservesReturnKeyType XCTAssertEqual(destination.returnKeyType, UIReturnKeyDone); } +- (void)testRestoringLineHeightGivesEachRunItsOwn +{ + // The input's own text, a run with its own line height, and a run with the input's line height that differs + // from the input in another part of its style + NSMutableParagraphStyle *clipping = [paragraphStyleWithLineHeight(24) mutableCopy]; + clipping.lineBreakMode = NSLineBreakByClipping; + NSMutableAttributedString *original = [[NSMutableAttributedString alloc] initWithString:@"ab" + attributes:attributesWithLineHeight(24)]; + [original appendAttributedString:[[NSAttributedString alloc] initWithString:@"cd" + attributes:attributesWithLineHeight(40)]]; + [original + appendAttributedString:[[NSAttributedString alloc] initWithString:@"ef" + attributes:@{NSParagraphStyleAttributeName : clipping}]]; + + NSAttributedString *omitted = RCTAttributedStringByOmittingLineHeight(original, paragraphStyleWithLineHeight(24)); + for (NSUInteger index = 0; index < omitted.length; index += 2) { + XCTAssertNotNil(paragraphStyleAtIndex(omitted, index)); + XCTAssertEqual(paragraphStyleAtIndex(omitted, index).minimumLineHeight, 0); + XCTAssertEqual(paragraphStyleAtIndex(omitted, index).maximumLineHeight, 0); + } + XCTAssertEqual(paragraphStyleAtIndex(omitted, 4).lineBreakMode, NSLineBreakByClipping); + + NSAttributedString *restored = RCTAttributedStringByRestoringLineHeight(omitted, paragraphStyleWithLineHeight(24)); + XCTAssertEqualObjects(restored, original); + + // The run that had the input's style follows the input; the others keep their own + NSAttributedString *restoredAfterChange = + RCTAttributedStringByRestoringLineHeight(omitted, paragraphStyleWithLineHeight(30)); + XCTAssertEqualObjects(paragraphStyleAtIndex(restoredAfterChange, 0), paragraphStyleWithLineHeight(30)); + XCTAssertEqualObjects(paragraphStyleAtIndex(restoredAfterChange, 2), paragraphStyleWithLineHeight(40)); + XCTAssertEqualObjects(paragraphStyleAtIndex(restoredAfterChange, 4), clipping); +} + +- (void)testRestoringLineHeightGivesUnrecordedTextTheInputsStyle +{ + // UIKit chooses the paragraph style of typed text, and gives it none in a unit test that no application hosts + NSMutableAttributedString *typed = [[NSMutableAttributedString alloc] initWithString:@"ab" + attributes:attributesWithLineHeight(0)]; + [typed appendAttributedString:[[NSAttributedString alloc] initWithString:@"cd"]]; + + NSAttributedString *restored = RCTAttributedStringByRestoringLineHeight(typed, paragraphStyleWithLineHeight(24)); + XCTAssertEqualObjects(paragraphStyleAtIndex(restored, 0), paragraphStyleWithLineHeight(24)); + XCTAssertEqualObjects(paragraphStyleAtIndex(restored, 2), paragraphStyleWithLineHeight(24)); +} + +- (void)testOmittingRecordsNothingForTextWithoutALineHeight +{ + // `setTextAndSelection` builds its string from the field's default attributes, whose line height + // is already omitted. + NSAttributedString *fromCommand = [[NSAttributedString alloc] initWithString:@"ab" + attributes:attributesWithLineHeight(0)]; + + NSAttributedString *restored = RCTAttributedStringByRestoringLineHeight( + RCTAttributedStringByOmittingLineHeight(fromCommand, paragraphStyleWithLineHeight(24)), + paragraphStyleWithLineHeight(24)); + XCTAssertEqual(paragraphStyleAtIndex(restored, 0).minimumLineHeight, 24); + XCTAssertEqual(paragraphStyleAtIndex(restored, 0).maximumLineHeight, 24); +} + +- (void)testSingleLineParagraphStyleReplacesOnlyModesThatWrap +{ + NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new]; + paragraphStyle.alignment = NSTextAlignmentRight; + + for (NSNumber *lineBreakMode in @[ @(NSLineBreakByWordWrapping), @(NSLineBreakByCharWrapping) ]) { + paragraphStyle.lineBreakMode = (NSLineBreakMode)lineBreakMode.integerValue; + NSParagraphStyle *singleLine = RCTSingleLineParagraphStyle(paragraphStyle); + XCTAssertEqual(singleLine.lineBreakMode, NSLineBreakByTruncatingTail); + XCTAssertEqual(singleLine.alignment, NSTextAlignmentRight); + } + + for (NSNumber *lineBreakMode in @[ + @(NSLineBreakByClipping), + @(NSLineBreakByTruncatingHead), + @(NSLineBreakByTruncatingMiddle), + @(NSLineBreakByTruncatingTail) + ]) { + paragraphStyle.lineBreakMode = (NSLineBreakMode)lineBreakMode.integerValue; + XCTAssertEqualObjects(RCTSingleLineParagraphStyle(paragraphStyle), paragraphStyle); + } +} + +- (void)testAttributedStringWithSingleLineParagraphStylesReplacesEachRunsStyle +{ + NSMutableParagraphStyle *wrapping = [NSMutableParagraphStyle new]; + wrapping.alignment = NSTextAlignmentCenter; + NSMutableParagraphStyle *clipping = [NSMutableParagraphStyle new]; + clipping.lineBreakMode = NSLineBreakByClipping; + NSMutableAttributedString *original = [[NSMutableAttributedString alloc] initWithString:@"ab"]; + [original + appendAttributedString:[[NSAttributedString alloc] initWithString:@"cd" + attributes:@{NSParagraphStyleAttributeName : wrapping}]]; + [original + appendAttributedString:[[NSAttributedString alloc] initWithString:@"ef" + attributes:@{NSParagraphStyleAttributeName : clipping}]]; + + NSAttributedString *singleLine = RCTAttributedStringWithSingleLineParagraphStyles(original); + + XCTAssertEqualObjects(singleLine.string, @"abcdef"); + // Text with no paragraph style gets none: the field gives it its own, which keeps to one line + XCTAssertNil([singleLine attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:NULL]); + NSParagraphStyle *replaced = [singleLine attribute:NSParagraphStyleAttributeName atIndex:2 effectiveRange:NULL]; + XCTAssertEqual(replaced.lineBreakMode, NSLineBreakByTruncatingTail); + XCTAssertEqual(replaced.alignment, NSTextAlignmentCenter); + XCTAssertEqualObjects([singleLine attribute:NSParagraphStyleAttributeName atIndex:4 effectiveRange:NULL], clipping); +} + @end