This repository was archived by the owner on Jan 30, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReactTextViewImprovedShadowNode.java
More file actions
364 lines (329 loc) · 14.3 KB
/
ReactTextViewImprovedShadowNode.java
File metadata and controls
364 lines (329 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
* @see https://github.com/fabriziobertoglio1987/react-native-improved
*
* @author Fabrizio Bertoglio https://github.com/fabriziobertoglio1987
*/
package com.text;
import static android.text.Layout.BREAK_STRATEGY_HIGH_QUALITY;
import static android.text.Layout.BREAK_STRATEGY_SIMPLE;
import static android.text.Layout.HYPHENATION_FREQUENCY_NONE;
import android.graphics.text.LineBreaker;
import android.os.Build;
import android.text.BoringLayout;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.Gravity;
import androidx.annotation.Nullable;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactNoCrashSoftException;
import com.facebook.react.bridge.ReactSoftExceptionLogger;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.NativeViewHierarchyOptimizer;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.ReactShadowNode;
import com.facebook.react.uimanager.Spacing;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.UIViewOperationQueue;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.facebook.react.views.text.FontMetricsUtil;
import com.facebook.react.views.text.ReactAbsoluteSizeSpan;
import com.facebook.react.views.text.ReactTextShadowNode;
import com.facebook.react.views.text.ReactTextUpdate;
import com.facebook.react.views.text.ReactTextViewManagerCallback;
import com.facebook.react.views.text.TextInlineViewPlaceholderSpan;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaMeasureMode;
import com.facebook.yoga.YogaMeasureOutput;
import com.facebook.yoga.YogaNode;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReactTextViewImprovedShadowNode extends ReactTextShadowNode {
// It's important to pass the ANTI_ALIAS_FLAG flag to the constructor rather than setting it
// later by calling setFlags. This is because the latter approach triggers a bug on Android 4.4.2.
// The bug is that unicode emoticons aren't measured properly which causes text to be clipped.
private static final TextPaint sTextPaintInstance = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
private @Nullable Spannable mPreparedSpannableText;
private boolean mShouldNotifyOnTextLayout;
private final YogaMeasureFunction mTextMeasureFunction =
new YogaMeasureFunction() {
@Override
public long measure(
YogaNode node,
float width,
YogaMeasureMode widthMode,
float height,
YogaMeasureMode heightMode) {
Spannable text =
Assertions.assertNotNull(
mPreparedSpannableText,
"Spannable element has not been prepared in onBeforeLayout");
Layout layout = measureSpannedText(text, width, widthMode);
if (mAdjustsFontSizeToFit) {
int initialFontSize = mTextAttributes.getEffectiveFontSize();
int currentFontSize = mTextAttributes.getEffectiveFontSize();
// Minimum font size is 4pts to match the iOS implementation.
int minimumFontSize =
(int) Math.max(mMinimumFontScale * initialFontSize, PixelUtil.toPixelFromDIP(4));
while (currentFontSize > minimumFontSize
&& (mNumberOfLines != UNSET && layout.getLineCount() > mNumberOfLines
|| heightMode != YogaMeasureMode.UNDEFINED && layout.getHeight() > height)) {
// TODO: We could probably use a smarter algorithm here. This will require 0(n)
// measurements
// based on the number of points the font size needs to be reduced by.
currentFontSize -= Math.max(1, (int) PixelUtil.toPixelFromDIP(1));
float ratio = (float) currentFontSize / (float) initialFontSize;
ReactAbsoluteSizeSpan[] sizeSpans =
text.getSpans(0, text.length(), ReactAbsoluteSizeSpan.class);
for (ReactAbsoluteSizeSpan span : sizeSpans) {
text.setSpan(
new ReactAbsoluteSizeSpan(
(int) Math.max((span.getSize() * ratio), minimumFontSize)),
text.getSpanStart(span),
text.getSpanEnd(span),
text.getSpanFlags(span));
text.removeSpan(span);
}
layout = measureSpannedText(text, width, widthMode);
}
}
if (mShouldNotifyOnTextLayout) {
ThemedReactContext themedReactContext = getThemedContext();
WritableArray lines =
FontMetricsUtil.getFontMetrics(
text, layout, sTextPaintInstance, themedReactContext);
WritableMap event = Arguments.createMap();
event.putArray("lines", lines);
if (themedReactContext.hasActiveReactInstance()) {
themedReactContext
.getJSModule(RCTEventEmitter.class)
.receiveEvent(getReactTag(), "topTextLayout", event);
} else {
ReactSoftExceptionLogger.logSoftException(
"ReactTextShadowNode",
new ReactNoCrashSoftException("Cannot get RCTEventEmitter, no CatalystInstance"));
}
}
final int lineCount =
mNumberOfLines == UNSET
? layout.getLineCount()
: Math.min(mNumberOfLines, layout.getLineCount());
// Instead of using `layout.getWidth()` (which may yield a significantly larger width for
// text that is wrapping), compute width using the longest line.
float layoutWidth = 0;
if (widthMode == YogaMeasureMode.EXACTLY) {
layoutWidth = width;
} else {
if (lineCount == 1) {
layoutWidth = (int) layout.getEllipsizedWidth();
} else {
for (int lineIndex = 0; lineIndex < lineCount; lineIndex++) {
boolean endsWithNewLine =
text.length() > 0 && text.charAt(layout.getLineEnd(lineIndex) - 1) == '\n';
float lineWidth =
endsWithNewLine ? layout.getLineMax(lineIndex) : layout.getLineWidth(lineIndex);
if (lineWidth > layoutWidth) {
layoutWidth = lineWidth;
}
}
}
if (widthMode == YogaMeasureMode.AT_MOST && layoutWidth > width) {
layoutWidth = width;
}
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
layoutWidth = (float) Math.ceil(layoutWidth);
}
float layoutHeight = height;
if (heightMode != YogaMeasureMode.EXACTLY) {
layoutHeight = layout.getLineBottom(lineCount - 1);
if (heightMode == YogaMeasureMode.AT_MOST && layoutHeight > height) {
layoutHeight = height;
}
}
return YogaMeasureOutput.make(layoutWidth, layoutHeight);
}
};
private final YogaBaselineFunction mTextBaselineFunction =
new YogaBaselineFunction() {
@Override
public float baseline(YogaNode node, float width, float height) {
Spannable text =
Assertions.assertNotNull(
mPreparedSpannableText,
"Spannable element has not been prepared in onBeforeLayout");
Layout layout = measureSpannedText(text, width, YogaMeasureMode.EXACTLY);
return layout.getLineBaseline(layout.getLineCount() - 1);
}
};
public ReactTextViewImprovedShadowNode() {
this(null);
}
public ReactTextViewImprovedShadowNode(
@Nullable ReactTextViewManagerCallback reactTextViewManagerCallback) {
super(reactTextViewManagerCallback);
initMeasureFunction();
}
private void initMeasureFunction() {
if (!isVirtual()) {
setMeasureFunction(mTextMeasureFunction);
setBaselineFunction(mTextBaselineFunction);
}
}
private Layout measureSpannedText(Spannable text, float width, YogaMeasureMode widthMode) {
// TODO(5578671): Handle text direction (see View#getTextDirectionHeuristic)
TextPaint textPaint = sTextPaintInstance;
textPaint.setTextSize(mTextAttributes.getEffectiveFontSize());
Layout layout;
BoringLayout.Metrics boring = BoringLayout.isBoring(text, textPaint);
float desiredWidth = boring == null ? Layout.getDesiredWidth(text, textPaint) : Float.NaN;
// technically, width should never be negative, but there is currently a bug in
boolean unconstrainedWidth = widthMode == YogaMeasureMode.UNDEFINED || width < 0;
Layout.Alignment alignment = Layout.Alignment.ALIGN_NORMAL;
switch (getTextAlign()) {
case Gravity.LEFT:
alignment = Layout.Alignment.ALIGN_NORMAL;
break;
case Gravity.RIGHT:
alignment = Layout.Alignment.ALIGN_OPPOSITE;
break;
case Gravity.CENTER_HORIZONTAL:
alignment = Layout.Alignment.ALIGN_CENTER;
break;
}
if (boring == null
&& (unconstrainedWidth
|| (!YogaConstants.isUndefined(desiredWidth) && desiredWidth <= width))) {
// Is used when the width is not known and the text is not boring, ie. if it contains
// unicode characters.
int hintWidth = (int) Math.ceil(desiredWidth);
StaticLayout.Builder builder =
StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, hintWidth)
.setAlignment(alignment)
.setLineSpacing(0.f, 1.f)
.setIncludePad(mIncludeFontPadding)
.setBreakStrategy(mTextBreakStrategy)
.setHyphenationFrequency(mHyphenationFrequency);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setJustificationMode(mJustificationMode);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setUseLineSpacingFromFallbacks(true);
}
layout = builder.build();
} else if (boring != null
&& (unconstrainedWidth || boring.width <= width)) {
// Is used for single-line, boring text when the width is either unknown or bigger
// than the width of the text.
layout =
BoringLayout.make(
text,
textPaint,
Math.max(boring.width, 0),
alignment,
1.f,
0.f,
boring,
mIncludeFontPadding);
} else {
// Is used for multiline, boring text and the width is known.
// Android 11+ introduces changes in text width calculation which leads to cases
// where the container is measured smaller than text. Math.ceil prevents it
// See T136756103 for investigation
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
width = (float) Math.ceil(width);
}
StaticLayout.Builder builder =
StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, (int) width)
.setAlignment(alignment)
.setLineSpacing(0.f, 1.f)
.setIncludePad(mIncludeFontPadding)
.setBreakStrategy(mTextBreakStrategy)
.setHyphenationFrequency(mHyphenationFrequency);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setUseLineSpacingFromFallbacks(true);
}
layout = builder.build();
}
return layout;
}
// Return text alignment according to LTR or RTL style
private int getTextAlign() {
int textAlign = mTextAlign;
if (getLayoutDirection() == YogaDirection.RTL) {
if (textAlign == Gravity.RIGHT) {
textAlign = Gravity.LEFT;
} else if (textAlign == Gravity.LEFT) {
textAlign = Gravity.RIGHT;
}
}
return textAlign;
}
@Override
public void onBeforeLayout(NativeViewHierarchyOptimizer nativeViewHierarchyOptimizer) {
mPreparedSpannableText =
spannedFromShadowNode(
this,
/* text (e.g. from `value` prop): */ null,
/* supportsInlineViews: */ true,
nativeViewHierarchyOptimizer);
markUpdated();
}
@Override
public void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) {
super.onCollectExtraUpdates(uiViewOperationQueue);
if (mPreparedSpannableText != null) {
ReactTextUpdate reactTextUpdate =
new ReactTextUpdate(
mPreparedSpannableText,
UNSET,
mContainsImages,
getPadding(Spacing.START),
getPadding(Spacing.TOP),
getPadding(Spacing.END),
getPadding(Spacing.BOTTOM),
getTextAlign(),
mTextBreakStrategy,
mJustificationMode);
uiViewOperationQueue.enqueueUpdateExtraData(getReactTag(), reactTextUpdate);
}
}
@ReactProp(name = "onTextLayout")
public void setShouldNotifyOnTextLayout(boolean shouldNotifyOnTextLayout) {
mShouldNotifyOnTextLayout = shouldNotifyOnTextLayout;
}
@Override
@Nullable
public Iterable<? extends ReactShadowNode> calculateLayoutOnChildren() {
// Run flexbox on and return the descendants which are inline views.
if (mInlineViews == null || mInlineViews.isEmpty()) {
return null;
}
Spanned text =
Assertions.assertNotNull(
this.mPreparedSpannableText,
"Spannable element has not been prepared in onBeforeLayout");
TextInlineViewPlaceholderSpan[] placeholders =
text.getSpans(0, text.length(), TextInlineViewPlaceholderSpan.class);
ArrayList<ReactShadowNode> shadowNodes = new ArrayList<>(placeholders.length);
for (TextInlineViewPlaceholderSpan placeholder : placeholders) {
ReactShadowNode child = mInlineViews.get(placeholder.getReactTag());
child.calculateLayout();
shadowNodes.add(child);
}
return shadowNodes;
}
}