Skip to content

Commit 39a0d2e

Browse files
committed
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: a 16 pt system font in a 24 pt line gets about 5 pt of extra leading, all of it above. 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. Without the line height, two lines of the font can fit in a field that held one, and a `UITextField` that is not being edited wraps its text when its paragraph style says to. The paragraph style the field draws with therefore also ends a line that would wrap with an ellipsis, as a text field does when it has no paragraph style. A `lineHeight` smaller than the font's line is drawn the same way. The field is then shorter than its text, which is centered on the field and extends equally above and below it. Chrome and Safari center the text of an `<input>` that is shorter than its line the same way, and clip it to the box. The field clips the placeholder and the text being edited, but not a value that is not being edited, which can overlap the views next to the field. Before, the compressed line put the text above the field, and the text being edited lost its upper part. Layout measures the field from the attributed string in the state, so that string keeps its paragraph styles. A private attribute records the paragraph style replaced in each range where it is not the input's own, such as a nested `<Text>` with its own `lineHeight`, and the text written back to the state gets each recorded style again. Text with no record, which is the input's own text and text typed into the field, gets the input's paragraph style. `updateProps:` and a change of the content size category set the default text attributes through one method, so a change of the content size category also keeps the event emitter attribute.
1 parent 94aee19 commit 39a0d2e

5 files changed

Lines changed: 636 additions & 13 deletions

File tree

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

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

9696
BOOL _hasInputAccessoryView;
9797
CGSize _previousContentSize;
98+
99+
/*
100+
* The input's paragraph style when the field draws without its line height, or nil. TextKit puts a line's extra
101+
* leading above the glyphs, where CSS splits it equally above and below them
102+
* (https://www.w3.org/TR/CSS2/visudet.html#leading). A single-line field gets the CSS placement by drawing without
103+
* the line height, because `UITextField` centers a line of the font's own height in the field.
104+
*/
105+
NSParagraphStyle *_omittedParagraphStyle;
98106
}
99107

100108
#pragma mark - UIView overrides
@@ -156,9 +164,7 @@ - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
156164

157165
if (UITraitCollection.currentTraitCollection.preferredContentSizeCategory !=
158166
previousTraitCollection.preferredContentSizeCategory) {
159-
const auto &newTextInputProps = static_cast<const TextInputProps &>(*_props);
160-
_backedTextInputView.defaultTextAttributes =
161-
RCTNSTextAttributesFromTextAttributes(newTextInputProps.getEffectiveTextAttributes(RCTFontSizeMultiplier()));
167+
[self _updateDefaultTextAttributesWithProps:static_cast<const TextInputProps &>(*_props)];
162168
}
163169
}
164170

@@ -327,12 +333,10 @@ - (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared &
327333
_backedTextInputView.placeholderColor = RCTUIColorFromSharedColor(newTextInputProps.placeholderTextColor);
328334
}
329335

330-
if (newTextInputProps.textAttributes != oldTextInputProps.textAttributes) {
331-
NSMutableDictionary<NSAttributedStringKey, id> *defaultAttributes =
332-
RCTNSTextAttributesFromTextAttributes(newTextInputProps.getEffectiveTextAttributes(RCTFontSizeMultiplier()));
333-
defaultAttributes[RCTAttributedStringEventEmitterKey] =
334-
_backedTextInputView.defaultTextAttributes[RCTAttributedStringEventEmitterKey];
335-
_backedTextInputView.defaultTextAttributes = defaultAttributes;
336+
// Only a single-line field omits the line height, so `multiline` changes the attributes too.
337+
if (newTextInputProps.textAttributes != oldTextInputProps.textAttributes ||
338+
newTextInputProps.multiline != oldTextInputProps.multiline) {
339+
[self _updateDefaultTextAttributesWithProps:newTextInputProps];
336340
}
337341

338342
if (newTextInputProps.selectionColor != oldTextInputProps.selectionColor) {
@@ -820,15 +824,23 @@ - (void)_updateState
820824
if (!_state) {
821825
return;
822826
}
823-
NSAttributedString *attributedString = _backedTextInputView.attributedText;
824827
auto data = _state->getData();
825-
_lastStringStateWasUpdatedWith = attributedString;
826-
data.attributedStringBox = RCTAttributedStringBoxFromNSAttributedString(attributedString);
828+
_lastStringStateWasUpdatedWith = _backedTextInputView.attributedText;
829+
data.attributedStringBox = RCTAttributedStringBoxFromNSAttributedString([self _attributedStringForState]);
827830
_mostRecentEventCount += _comingFromJS ? 0 : 1;
828831
data.mostRecentEventCount = _mostRecentEventCount;
829832
_state->updateState(std::move(data));
830833
}
831834

835+
// Returns the field's text with the paragraph styles the field draws without, which is the form the state holds.
836+
- (NSAttributedString *)_attributedStringForState
837+
{
838+
NSAttributedString *attributedString = _backedTextInputView.attributedText;
839+
return _omittedParagraphStyle != nil
840+
? RCTAttributedStringByRestoringLineHeight(attributedString, _omittedParagraphStyle)
841+
: attributedString;
842+
}
843+
832844
- (AttributedString::Range)_selectionRange
833845
{
834846
UITextRange *selectedTextRange = _backedTextInputView.selectedTextRange;
@@ -860,11 +872,32 @@ - (void)_restoreTextSelectionAndIgnoreCaretChange:(BOOL)ignore
860872
[_backedTextInputView setSelectedTextRange:range notifyDelegate:YES];
861873
}
862874

875+
// Sets the field's default text attributes from `props`, and `_omittedParagraphStyle` with them.
876+
- (void)_updateDefaultTextAttributesWithProps:(const TextInputProps &)props
877+
{
878+
NSMutableDictionary<NSAttributedStringKey, id> *attributes =
879+
RCTNSTextAttributesFromTextAttributes(props.getEffectiveTextAttributes(RCTFontSizeMultiplier()));
880+
NSParagraphStyle *paragraphStyle = attributes[NSParagraphStyleAttributeName];
881+
_omittedParagraphStyle = !props.multiline && paragraphStyle.maximumLineHeight > 0 ? [paragraphStyle copy] : nil;
882+
if (_omittedParagraphStyle != nil) {
883+
attributes[NSParagraphStyleAttributeName] = RCTParagraphStyleByOmittingLineHeight(paragraphStyle);
884+
}
885+
attributes[RCTAttributedStringEventEmitterKey] =
886+
_backedTextInputView.defaultTextAttributes[RCTAttributedStringEventEmitterKey];
887+
_backedTextInputView.defaultTextAttributes = attributes;
888+
}
889+
863890
- (void)_setAttributedString:(NSAttributedString *)attributedString
864891
{
865-
if ([self _textOf:attributedString equals:_backedTextInputView.attributedText]) {
892+
// Compare with the paragraph styles restored: the field draws with other styles than the state's text has, so
893+
// only the restored text can match it.
894+
NSAttributedString *oldAttributedString = [self _attributedStringForState];
895+
if ([self _textOf:attributedString equals:oldAttributedString]) {
866896
return;
867897
}
898+
if (_omittedParagraphStyle != nil) {
899+
attributedString = RCTAttributedStringByOmittingLineHeight(attributedString, _omittedParagraphStyle);
900+
}
868901
UITextRange *selectedRange = _backedTextInputView.selectedTextRange;
869902
NSInteger oldTextLength = _backedTextInputView.attributedText.string.length;
870903
_backedTextInputView.attributedText = attributedString;

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

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

21+
/*
22+
* Returns the paragraph style a single-line field draws with in place of `paragraphStyle`: one with no line
23+
* height, which keeps to one line where `paragraphStyle` would wrap.
24+
*/
25+
NSParagraphStyle *RCTParagraphStyleByOmittingLineHeight(NSParagraphStyle *paragraphStyle);
26+
27+
/*
28+
* Returns `attributedString` with each paragraph style that has a line height replaced as
29+
* `RCTParagraphStyleByOmittingLineHeight` does. A private attribute records the replaced style of each range
30+
* where it is not `inputParagraphStyle`, the input's own, so that the other ranges follow the input when its
31+
* style changes.
32+
*/
33+
NSAttributedString *RCTAttributedStringByOmittingLineHeight(
34+
NSAttributedString *attributedString,
35+
NSParagraphStyle *inputParagraphStyle);
36+
37+
/*
38+
* Reverses `RCTAttributedStringByOmittingLineHeight`: each range gets back the paragraph style recorded for it. A
39+
* range with no record, such as the input's own text and text typed into the field, gets `inputParagraphStyle`.
40+
*/
41+
NSAttributedString *RCTAttributedStringByRestoringLineHeight(
42+
NSAttributedString *attributedString,
43+
NSParagraphStyle *inputParagraphStyle);
44+
2145
UITextAutocorrectionType RCTUITextAutocorrectionTypeFromOptionalBool(std::optional<bool> autoCorrect);
2246

2347
UITextAutocapitalizationType RCTUITextAutocapitalizationTypeFromAutocapitalizationType(

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

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

56+
static const NSAttributedStringKey RCTOmittedParagraphStyleAttributeName = @"RCTOmittedParagraphStyle";
57+
58+
NSParagraphStyle *RCTParagraphStyleByOmittingLineHeight(NSParagraphStyle *paragraphStyle)
59+
{
60+
NSMutableParagraphStyle *copy = [paragraphStyle mutableCopy];
61+
copy.minimumLineHeight = 0;
62+
copy.maximumLineHeight = 0;
63+
// A text field that is not being edited wraps its text when the style says to, and without the line height a
64+
// second line can fit in the field. End the line with an ellipsis instead, as a field does with no style.
65+
if (copy.lineBreakMode == NSLineBreakByWordWrapping || copy.lineBreakMode == NSLineBreakByCharWrapping) {
66+
copy.lineBreakMode = NSLineBreakByTruncatingTail;
67+
}
68+
return copy;
69+
}
70+
71+
NSAttributedString *RCTAttributedStringByOmittingLineHeight(
72+
NSAttributedString *attributedString,
73+
NSParagraphStyle *inputParagraphStyle)
74+
{
75+
NSMutableAttributedString *copy = [attributedString mutableCopy];
76+
[attributedString enumerateAttribute:NSParagraphStyleAttributeName
77+
inRange:NSMakeRange(0, attributedString.length)
78+
options:0
79+
usingBlock:^(NSParagraphStyle *paragraphStyle, NSRange range, BOOL *stop) {
80+
// Leave a style with no line height as it is: a record of it would keep the
81+
// input's line height from the range on restore.
82+
if (paragraphStyle.maximumLineHeight <= 0) {
83+
return;
84+
}
85+
[copy addAttribute:NSParagraphStyleAttributeName
86+
value:RCTParagraphStyleByOmittingLineHeight(paragraphStyle)
87+
range:range];
88+
if (![paragraphStyle isEqual:inputParagraphStyle]) {
89+
[copy addAttribute:RCTOmittedParagraphStyleAttributeName
90+
value:paragraphStyle
91+
range:range];
92+
}
93+
}];
94+
return copy;
95+
}
96+
97+
NSAttributedString *RCTAttributedStringByRestoringLineHeight(
98+
NSAttributedString *attributedString,
99+
NSParagraphStyle *inputParagraphStyle)
100+
{
101+
NSRange fullRange = NSMakeRange(0, attributedString.length);
102+
NSMutableAttributedString *copy = [attributedString mutableCopy];
103+
[copy removeAttribute:RCTOmittedParagraphStyleAttributeName range:fullRange];
104+
[attributedString enumerateAttribute:RCTOmittedParagraphStyleAttributeName
105+
inRange:fullRange
106+
options:0
107+
usingBlock:^(NSParagraphStyle *omittedParagraphStyle, NSRange range, BOOL *stop) {
108+
[copy addAttribute:NSParagraphStyleAttributeName
109+
value:omittedParagraphStyle ?: inputParagraphStyle
110+
range:range];
111+
}];
112+
return copy;
113+
}
114+
56115
UITextAutocorrectionType RCTUITextAutocorrectionTypeFromOptionalBool(std::optional<bool> autoCorrect)
57116
{
58117
return autoCorrect.has_value() ? (*autoCorrect ? UITextAutocorrectionTypeYes : UITextAutocorrectionTypeNo)

0 commit comments

Comments
 (0)