Skip to content

Commit 9fee22b

Browse files
ideclaude
andcommitted
Center a single-line iOS TextInput's text within its lineHeight
A single-line `TextInput` whose `lineHeight` is larger than its font draws its value, its placeholder and typed text at the bottom of the line instead of in the middle. `lineHeight` reaches the field as the paragraph style's minimum and maximum line height, and TextKit puts all of the extra leading above the glyphs, so a 16 pt font in a 24 pt line is drawn 4 pt low. CSS splits the leading equally above and below the glyphs (https://www.w3.org/TR/CSS2/visudet.html#leading). Layout already makes a single-line field as tall as its line, and `UITextField` centers the font's own line in its text rect. A single-line field therefore draws without the line height: it is removed from the default text attributes, which also style the placeholder and typed text, and from the attributed text the field is given. Multi-line fields keep the line height, which spaces their lines. Layout measures the field from the attributed string in the state, so that string keeps its line heights. A private attribute records the line height removed from each range of the field's text, and the text written back to the state gets each range's own value again. Text typed into an empty field has no record and gets the input's line height. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 94aee19 commit 9fee22b

5 files changed

Lines changed: 246 additions & 6 deletions

File tree

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

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,22 @@ @implementation RCTTextInputComponentView {
9595

9696
BOOL _hasInputAccessoryView;
9797
CGSize _previousContentSize;
98+
99+
/*
100+
* The input's own line height when a single-line field leaves line heights
101+
* out of the text it draws, or zero when it leaves none out.
102+
*
103+
* `lineHeight` reaches the field as the paragraph style's minimum and maximum
104+
* line height, and TextKit puts all of the extra leading above the glyphs.
105+
* CSS splits it equally above and below
106+
* (https://www.w3.org/TR/CSS2/visudet.html#leading). `UITextField` centers
107+
* the font's own line in its text rect, which layout makes as tall as the
108+
* line, so a single-line field gets the CSS placement by drawing without the
109+
* line height. The text in the state keeps each run's line height, because
110+
* layout measures the field from that text. A multi-line field draws with
111+
* the line height to space its lines.
112+
*/
113+
CGFloat _omittedLineHeight;
98114
}
99115

100116
#pragma mark - UIView overrides
@@ -157,8 +173,7 @@ - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
157173
if (UITraitCollection.currentTraitCollection.preferredContentSizeCategory !=
158174
previousTraitCollection.preferredContentSizeCategory) {
159175
const auto &newTextInputProps = static_cast<const TextInputProps &>(*_props);
160-
_backedTextInputView.defaultTextAttributes =
161-
RCTNSTextAttributesFromTextAttributes(newTextInputProps.getEffectiveTextAttributes(RCTFontSizeMultiplier()));
176+
_backedTextInputView.defaultTextAttributes = [self _defaultTextAttributesFor:newTextInputProps];
162177
}
163178
}
164179

@@ -327,9 +342,11 @@ - (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared &
327342
_backedTextInputView.placeholderColor = RCTUIColorFromSharedColor(newTextInputProps.placeholderTextColor);
328343
}
329344

330-
if (newTextInputProps.textAttributes != oldTextInputProps.textAttributes) {
345+
// Only a single-line field omits the line height, so `multiline` changes the attributes too.
346+
if (newTextInputProps.textAttributes != oldTextInputProps.textAttributes ||
347+
newTextInputProps.multiline != oldTextInputProps.multiline) {
331348
NSMutableDictionary<NSAttributedStringKey, id> *defaultAttributes =
332-
RCTNSTextAttributesFromTextAttributes(newTextInputProps.getEffectiveTextAttributes(RCTFontSizeMultiplier()));
349+
[self _defaultTextAttributesFor:newTextInputProps];
333350
defaultAttributes[RCTAttributedStringEventEmitterKey] =
334351
_backedTextInputView.defaultTextAttributes[RCTAttributedStringEventEmitterKey];
335352
_backedTextInputView.defaultTextAttributes = defaultAttributes;
@@ -823,7 +840,9 @@ - (void)_updateState
823840
NSAttributedString *attributedString = _backedTextInputView.attributedText;
824841
auto data = _state->getData();
825842
_lastStringStateWasUpdatedWith = attributedString;
826-
data.attributedStringBox = RCTAttributedStringBoxFromNSAttributedString(attributedString);
843+
data.attributedStringBox = RCTAttributedStringBoxFromNSAttributedString(
844+
_omittedLineHeight > 0 ? RCTAttributedStringByRestoringLineHeight(attributedString, _omittedLineHeight)
845+
: attributedString);
827846
_mostRecentEventCount += _comingFromJS ? 0 : 1;
828847
data.mostRecentEventCount = _mostRecentEventCount;
829848
_state->updateState(std::move(data));
@@ -860,11 +879,36 @@ - (void)_restoreTextSelectionAndIgnoreCaretChange:(BOOL)ignore
860879
[_backedTextInputView setSelectedTextRange:range notifyDelegate:YES];
861880
}
862881

882+
// Returns the default text attributes that the field draws with, and updates `_omittedLineHeight`.
883+
- (NSMutableDictionary<NSAttributedStringKey, id> *)_defaultTextAttributesFor:(const TextInputProps &)props
884+
{
885+
NSMutableDictionary<NSAttributedStringKey, id> *attributes =
886+
RCTNSTextAttributesFromTextAttributes(props.getEffectiveTextAttributes(RCTFontSizeMultiplier()));
887+
NSParagraphStyle *paragraphStyle = attributes[NSParagraphStyleAttributeName];
888+
_omittedLineHeight = props.multiline ? 0 : paragraphStyle.maximumLineHeight;
889+
if (_omittedLineHeight > 0) {
890+
NSMutableParagraphStyle *drawnParagraphStyle = [paragraphStyle mutableCopy];
891+
drawnParagraphStyle.minimumLineHeight = 0;
892+
drawnParagraphStyle.maximumLineHeight = 0;
893+
attributes[NSParagraphStyleAttributeName] = drawnParagraphStyle;
894+
}
895+
return attributes;
896+
}
897+
863898
- (void)_setAttributedString:(NSAttributedString *)attributedString
864899
{
865-
if ([self _textOf:attributedString equals:_backedTextInputView.attributedText]) {
900+
// Compared with the line heights in place: text typed into an empty field carries no record of the line height
901+
// it omits, so the two strings can only match in that form.
902+
NSAttributedString *oldAttributedString = _backedTextInputView.attributedText;
903+
if (_omittedLineHeight > 0) {
904+
oldAttributedString = RCTAttributedStringByRestoringLineHeight(oldAttributedString, _omittedLineHeight);
905+
}
906+
if ([self _textOf:attributedString equals:oldAttributedString]) {
866907
return;
867908
}
909+
if (_omittedLineHeight > 0) {
910+
attributedString = RCTAttributedStringByOmittingLineHeight(attributedString);
911+
}
868912
UITextRange *selectedRange = _backedTextInputView.selectedTextRange;
869913
NSInteger oldTextLength = _backedTextInputView.attributedText.string.length;
870914
_backedTextInputView.attributedText = attributedString;

‎packages/react-native/React/Fabric/Mounting/ComponentViews/TextInput/RCTTextInputUtils.h‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,20 @@ void RCTCopyBackedTextInput(
1818
UIView<RCTBackedTextInputViewProtocol> *fromTextInput,
1919
UIView<RCTBackedTextInputViewProtocol> *toTextInput);
2020

21+
/*
22+
* Returns `attributedString` with the minimum and maximum line height of each paragraph style set to zero. A
23+
* private attribute records the line height that was removed from each range.
24+
*/
25+
NSAttributedString *RCTAttributedStringByOmittingLineHeight(NSAttributedString *attributedString);
26+
27+
/*
28+
* Reverses `RCTAttributedStringByOmittingLineHeight`: each range gets back the line height recorded for it. A
29+
* range with no record, such as text typed into an empty field, gets `defaultLineHeight`.
30+
*/
31+
NSAttributedString *RCTAttributedStringByRestoringLineHeight(
32+
NSAttributedString *attributedString,
33+
CGFloat defaultLineHeight);
34+
2135
UITextAutocorrectionType RCTUITextAutocorrectionTypeFromOptionalBool(std::optional<bool> autoCorrect);
2236

2337
UITextAutocapitalizationType RCTUITextAutocapitalizationTypeFromAutocapitalizationType(

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

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,61 @@ void RCTCopyBackedTextInput(
5353
[toTextInput setSelectedTextRange:fromTextInput.selectedTextRange notifyDelegate:NO];
5454
}
5555

56+
static const NSAttributedStringKey RCTOmittedLineHeightAttributeName = @"RCTOmittedLineHeight";
57+
58+
static NSParagraphStyle *RCTParagraphStyleWithLineHeight(NSParagraphStyle *paragraphStyle, CGFloat lineHeight)
59+
{
60+
NSMutableParagraphStyle *copy = [paragraphStyle mutableCopy];
61+
copy.minimumLineHeight = lineHeight;
62+
copy.maximumLineHeight = lineHeight;
63+
return copy;
64+
}
65+
66+
NSAttributedString *RCTAttributedStringByOmittingLineHeight(NSAttributedString *attributedString)
67+
{
68+
NSMutableAttributedString *copy = [attributedString mutableCopy];
69+
[attributedString enumerateAttribute:NSParagraphStyleAttributeName
70+
inRange:NSMakeRange(0, attributedString.length)
71+
options:0
72+
usingBlock:^(NSParagraphStyle *paragraphStyle, NSRange range, BOOL *stop) {
73+
// A style with no line height has nothing to omit, and a record of 0
74+
// would override the input's own line height on restore.
75+
if (paragraphStyle != nil && paragraphStyle.maximumLineHeight > 0) {
76+
[copy addAttribute:RCTOmittedLineHeightAttributeName
77+
value:@(paragraphStyle.maximumLineHeight)
78+
range:range];
79+
[copy addAttribute:NSParagraphStyleAttributeName
80+
value:RCTParagraphStyleWithLineHeight(paragraphStyle, 0)
81+
range:range];
82+
}
83+
}];
84+
return copy;
85+
}
86+
87+
NSAttributedString *RCTAttributedStringByRestoringLineHeight(
88+
NSAttributedString *attributedString,
89+
CGFloat defaultLineHeight)
90+
{
91+
NSRange fullRange = NSMakeRange(0, attributedString.length);
92+
NSMutableAttributedString *copy = [attributedString mutableCopy];
93+
[copy removeAttribute:RCTOmittedLineHeightAttributeName range:fullRange];
94+
[attributedString
95+
enumerateAttributesInRange:fullRange
96+
options:0
97+
usingBlock:^(NSDictionary<NSAttributedStringKey, id> *attributes, NSRange range, BOOL *stop) {
98+
NSParagraphStyle *paragraphStyle = attributes[NSParagraphStyleAttributeName];
99+
NSNumber *omittedLineHeight = attributes[RCTOmittedLineHeightAttributeName];
100+
CGFloat lineHeight =
101+
omittedLineHeight != nil ? omittedLineHeight.doubleValue : defaultLineHeight;
102+
if (paragraphStyle != nil) {
103+
[copy addAttribute:NSParagraphStyleAttributeName
104+
value:RCTParagraphStyleWithLineHeight(paragraphStyle, lineHeight)
105+
range:range];
106+
}
107+
}];
108+
return copy;
109+
}
110+
56111
UITextAutocorrectionType RCTUITextAutocorrectionTypeFromOptionalBool(std::optional<bool> autoCorrect)
57112
{
58113
return autoCorrect.has_value() ? (*autoCorrect ? UITextAutocorrectionTypeYes : UITextAutocorrectionTypeNo)
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#import <React/RCTBackedTextInputViewProtocol.h>
9+
#import <React/RCTTextInputComponentView.h>
10+
#import <XCTest/XCTest.h>
11+
#import <react/renderer/components/iostextinput/TextInputProps.h>
12+
#import <react/renderer/components/iostextinput/TextInputShadowNode.h>
13+
14+
using namespace facebook::react;
15+
16+
static std::shared_ptr<const TextInputProps> propsWithLineHeight(bool multiline)
17+
{
18+
auto props = std::make_shared<TextInputProps>();
19+
props->multiline = multiline;
20+
// A unit test has no application to read the content size category from, so `RCTFontSizeMultiplier()` is 0 here
21+
// and would scale the line height to 0. Without font scaling the field gets the line height as written.
22+
props->textAttributes.allowFontScaling = false;
23+
props->textAttributes.fontSize = 16;
24+
props->textAttributes.lineHeight = 40;
25+
return props;
26+
}
27+
28+
static NSParagraphStyle *defaultParagraphStyle(RCTTextInputComponentView *view)
29+
{
30+
UIView<RCTBackedTextInputViewProtocol> *backedTextInputView = [view valueForKey:@"_backedTextInputView"];
31+
return backedTextInputView.defaultTextAttributes[NSParagraphStyleAttributeName];
32+
}
33+
34+
@interface RCTTextInputComponentViewTests : XCTestCase
35+
@end
36+
37+
@implementation RCTTextInputComponentViewTests
38+
39+
- (void)testSingleLineInputDrawsWithoutLineHeight
40+
{
41+
RCTTextInputComponentView *view = [RCTTextInputComponentView new];
42+
[view updateProps:propsWithLineHeight(false) oldProps:TextInputShadowNode::defaultSharedProps()];
43+
NSParagraphStyle *paragraphStyle = defaultParagraphStyle(view);
44+
45+
XCTAssertNotNil(paragraphStyle);
46+
XCTAssertEqual(paragraphStyle.minimumLineHeight, 0);
47+
XCTAssertEqual(paragraphStyle.maximumLineHeight, 0);
48+
// The state gets the line height back, because layout measures the field from it.
49+
XCTAssertEqual([[view valueForKey:@"_omittedLineHeight"] doubleValue], 40);
50+
}
51+
52+
- (void)testMultilineInputDrawsWithLineHeight
53+
{
54+
RCTTextInputComponentView *view = [RCTTextInputComponentView new];
55+
[view updateProps:propsWithLineHeight(true) oldProps:TextInputShadowNode::defaultSharedProps()];
56+
57+
XCTAssertEqual(defaultParagraphStyle(view).minimumLineHeight, 40);
58+
XCTAssertEqual(defaultParagraphStyle(view).maximumLineHeight, 40);
59+
}
60+
61+
- (void)testInputThatBecomesMultilineDrawsWithLineHeight
62+
{
63+
RCTTextInputComponentView *view = [RCTTextInputComponentView new];
64+
auto singleLineProps = propsWithLineHeight(false);
65+
[view updateProps:singleLineProps oldProps:TextInputShadowNode::defaultSharedProps()];
66+
[view updateProps:propsWithLineHeight(true) oldProps:singleLineProps];
67+
68+
XCTAssertEqual(defaultParagraphStyle(view).minimumLineHeight, 40);
69+
XCTAssertEqual(defaultParagraphStyle(view).maximumLineHeight, 40);
70+
}
71+
72+
@end

‎packages/react-native/React/Tests/Text/RCTTextInputUtilsTest.mm‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,19 @@
1010
#import <React/RCTUITextView.h>
1111
#import <XCTest/XCTest.h>
1212

13+
static NSDictionary<NSAttributedStringKey, id> *attributesWithLineHeight(CGFloat lineHeight)
14+
{
15+
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
16+
paragraphStyle.minimumLineHeight = lineHeight;
17+
paragraphStyle.maximumLineHeight = lineHeight;
18+
return @{NSParagraphStyleAttributeName : paragraphStyle};
19+
}
20+
21+
static NSParagraphStyle *paragraphStyleAtIndex(NSAttributedString *attributedString, NSUInteger index)
22+
{
23+
return [attributedString attribute:NSParagraphStyleAttributeName atIndex:index effectiveRange:NULL];
24+
}
25+
1326
@interface RCTTextInputUtilsTest : XCTestCase
1427
@end
1528

@@ -37,4 +50,46 @@ - (void)testCopyBackedTextInputPreservesReturnKeyType
3750
XCTAssertEqual(destination.returnKeyType, UIReturnKeyDone);
3851
}
3952

53+
- (void)testRestoringLineHeightGivesEachRunItsOwn
54+
{
55+
NSMutableAttributedString *original = [[NSMutableAttributedString alloc] initWithString:@"ab"
56+
attributes:attributesWithLineHeight(24)];
57+
[original appendAttributedString:[[NSAttributedString alloc] initWithString:@"cd"
58+
attributes:attributesWithLineHeight(40)]];
59+
60+
NSAttributedString *omitted = RCTAttributedStringByOmittingLineHeight(original);
61+
XCTAssertNotNil(paragraphStyleAtIndex(omitted, 0));
62+
XCTAssertEqual(paragraphStyleAtIndex(omitted, 0).maximumLineHeight, 0);
63+
XCTAssertNotNil(paragraphStyleAtIndex(omitted, 2));
64+
XCTAssertEqual(paragraphStyleAtIndex(omitted, 2).maximumLineHeight, 0);
65+
66+
NSAttributedString *restored = RCTAttributedStringByRestoringLineHeight(omitted, 24);
67+
XCTAssertEqual(paragraphStyleAtIndex(restored, 0).minimumLineHeight, 24);
68+
XCTAssertEqual(paragraphStyleAtIndex(restored, 0).maximumLineHeight, 24);
69+
XCTAssertEqual(paragraphStyleAtIndex(restored, 2).minimumLineHeight, 40);
70+
XCTAssertEqual(paragraphStyleAtIndex(restored, 2).maximumLineHeight, 40);
71+
}
72+
73+
- (void)testRestoringLineHeightGivesUnrecordedTextTheDefault
74+
{
75+
NSAttributedString *typed = [[NSAttributedString alloc] initWithString:@"ab" attributes:attributesWithLineHeight(0)];
76+
77+
NSAttributedString *restored = RCTAttributedStringByRestoringLineHeight(typed, 24);
78+
XCTAssertEqual(paragraphStyleAtIndex(restored, 0).minimumLineHeight, 24);
79+
XCTAssertEqual(paragraphStyleAtIndex(restored, 0).maximumLineHeight, 24);
80+
}
81+
82+
- (void)testOmittingRecordsNothingForTextWithoutALineHeight
83+
{
84+
// `setTextAndSelection` builds its string from the field's default attributes, whose line height
85+
// is already omitted.
86+
NSAttributedString *fromCommand = [[NSAttributedString alloc] initWithString:@"ab"
87+
attributes:attributesWithLineHeight(0)];
88+
89+
NSAttributedString *restored =
90+
RCTAttributedStringByRestoringLineHeight(RCTAttributedStringByOmittingLineHeight(fromCommand), 24);
91+
XCTAssertEqual(paragraphStyleAtIndex(restored, 0).minimumLineHeight, 24);
92+
XCTAssertEqual(paragraphStyleAtIndex(restored, 0).maximumLineHeight, 24);
93+
}
94+
4095
@end

0 commit comments

Comments
 (0)