Skip to content

Commit 60addfa

Browse files
Mark Verlingierimeta-codesync[bot]
authored andcommitted
Measure text lines for onTextLayout
Summary: Fantom didn't deliver `onTextLayout`: the platform-agnostic C++ `TextLayoutManager` had no `measureLines`, so `ParagraphShadowNode` only logged a warning. This adds a virtual `measureLines` to that `TextLayoutManager`, whose base implementation returns no lines. Fantom's `FantomTextLayoutManager` overrides it with the layout it paints screenshots with, so `onTextLayout` reports the lines Fantom draws. - Text cut by `numberOfLines` ends with a tail ellipsis in the reported lines and the screenshot, except after an inline view or emoji on the last line. - Selectable text is now painted, and baseline alignment uses the measured lines. - Other users of the C++ `TextLayoutManager` measure no lines: they no longer log the warning and still send no `onTextLayout` event. Changelog: [Internal] Reviewed By: rubennorte Differential Revision: D134743317
1 parent ce56c6c commit 60addfa

9 files changed

Lines changed: 536 additions & 18 deletions

File tree

‎packages/react-native/Libraries/Text/__tests__/Text-itest.js‎

Lines changed: 296 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
1212

1313
import type {HostInstance} from 'react-native';
14-
import type {AccessibilityProps} from 'react-native';
14+
import type {AccessibilityProps, TextLayoutEvent} from 'react-native';
1515

1616
import accessibilityPropsSuite, {
1717
rolePropSuite,
@@ -22,7 +22,7 @@ import * as Fantom from '@react-native/fantom';
2222
import nullthrows from 'nullthrows';
2323
import * as React from 'react';
2424
import {createRef} from 'react';
25-
import {Text} from 'react-native';
25+
import {Text, View} from 'react-native';
2626

2727
const TEST_TEXT = 'the text';
2828

@@ -651,6 +651,300 @@ describe('<Text>', () => {
651651
});
652652
});
653653

654+
describe('onTextLayout', () => {
655+
it('reports each line where it is drawn', () => {
656+
const lines: Array<{
657+
text: string,
658+
x: number,
659+
width: number,
660+
capHeight: number,
661+
xHeight: number,
662+
height: number,
663+
ascender: number,
664+
descender: number,
665+
}> = [];
666+
const root = Fantom.createRoot();
667+
668+
Fantom.runTask(() => {
669+
root.render(
670+
<Text
671+
onTextLayout={event => {
672+
for (const line of event.nativeEvent.lines) {
673+
lines.push({
674+
text: line.text,
675+
x: line.x,
676+
width: line.width,
677+
capHeight: line.capHeight,
678+
xHeight: line.xHeight,
679+
height: line.height,
680+
ascender: line.ascender,
681+
descender: line.descender,
682+
});
683+
}
684+
}}
685+
style={{width: 200, textAlign: 'center'}}>
686+
{TEST_TEXT}
687+
</Text>,
688+
);
689+
});
690+
Fantom.flushAllNativeEvents();
691+
692+
expect(lines).toHaveLength(1);
693+
expect(lines[0].text).toBe(TEST_TEXT);
694+
expect(lines[0].width).toBeGreaterThan(0);
695+
expect(lines[0].width).toBeLessThan(200);
696+
expect(lines[0].x).toBeCloseTo((200 - lines[0].width) / 2);
697+
expect(lines[0].xHeight).toBeGreaterThan(0);
698+
expect(lines[0].capHeight).toBeGreaterThan(lines[0].xHeight);
699+
expect(lines[0].ascender).toBeGreaterThan(lines[0].capHeight);
700+
expect(lines[0].ascender + lines[0].descender).toBeCloseTo(
701+
lines[0].height,
702+
);
703+
});
704+
705+
it('draws the lines it reports when only `numberOfLines` changes', () => {
706+
const LONG_TEXT = 'the text that is long enough to wrap onto more lines';
707+
const renderText = (
708+
root: ReturnType<typeof Fantom.createRoot>,
709+
numberOfLines: number,
710+
): ReadonlyArray<string> => {
711+
let reportedLines: ReadonlyArray<string> = [];
712+
Fantom.runTask(() => {
713+
root.render(
714+
<Text
715+
numberOfLines={numberOfLines}
716+
onTextLayout={event => {
717+
reportedLines = event.nativeEvent.lines.map(line => line.text);
718+
}}
719+
style={{width: 100, height: 60}}>
720+
{LONG_TEXT}
721+
</Text>,
722+
);
723+
});
724+
Fantom.flushAllNativeEvents();
725+
return reportedLines;
726+
};
727+
728+
const changedRoot = Fantom.createRoot();
729+
expect(renderText(changedRoot, 2)).toHaveLength(2);
730+
const twoLines = changedRoot.takeScreenshot();
731+
expect(renderText(changedRoot, 1)).toHaveLength(1);
732+
const oneLineRoot = Fantom.createRoot();
733+
renderText(oneLineRoot, 1);
734+
735+
expect(twoLines.isEqual(oneLineRoot.takeScreenshot())).toBe(false);
736+
expect(
737+
changedRoot.takeScreenshot().isEqual(oneLineRoot.takeScreenshot()),
738+
).toBe(true);
739+
});
740+
741+
it('draws the lines it reports for a selectable text', () => {
742+
const renderText = (
743+
root: ReturnType<typeof Fantom.createRoot>,
744+
selectable: boolean,
745+
): ReadonlyArray<string> => {
746+
let reportedLines: ReadonlyArray<string> = [];
747+
Fantom.runTask(() => {
748+
root.render(
749+
<Text
750+
onTextLayout={event => {
751+
reportedLines = event.nativeEvent.lines.map(line => line.text);
752+
}}
753+
selectable={selectable}
754+
style={{width: 100}}>
755+
{TEST_TEXT}
756+
</Text>,
757+
);
758+
});
759+
Fantom.flushAllNativeEvents();
760+
return reportedLines;
761+
};
762+
763+
const selectableRoot = Fantom.createRoot();
764+
expect(renderText(selectableRoot, true)).toEqual([TEST_TEXT]);
765+
const plainRoot = Fantom.createRoot();
766+
renderText(plainRoot, false);
767+
const emptyRoot = Fantom.createRoot();
768+
Fantom.runTask(() => {
769+
emptyRoot.render(<Text style={{width: 100}} />);
770+
});
771+
772+
expect(
773+
selectableRoot.takeScreenshot().isEqual(plainRoot.takeScreenshot()),
774+
).toBe(true);
775+
expect(
776+
selectableRoot.takeScreenshot().isEqual(emptyRoot.takeScreenshot()),
777+
).toBe(false);
778+
});
779+
780+
it('ends a cut last line with an ellipsis (plain text only)', () => {
781+
const LONG_TEXT =
782+
'The quick brown fox jumps over the lazy dog again and again';
783+
const linesByText: {[name: string]: ReadonlyArray<string>} = {};
784+
let blankLineLines: TextLayoutEvent['nativeEvent']['lines'] = [];
785+
const reportLines =
786+
(name: string) =>
787+
(event: TextLayoutEvent): void => {
788+
linesByText[name] = event.nativeEvent.lines.map(line => line.text);
789+
if (name === 'blankLine') {
790+
blankLineLines = event.nativeEvent.lines;
791+
}
792+
};
793+
794+
const root = Fantom.createRoot();
795+
Fantom.runTask(() => {
796+
root.render(
797+
<View style={{width: 100}}>
798+
<Text numberOfLines={2} onTextLayout={reportLines('cut')}>
799+
{LONG_TEXT}
800+
</Text>
801+
<Text numberOfLines={2} onTextLayout={reportLines('fitting')}>
802+
The quick fox
803+
</Text>
804+
<Text numberOfLines={2} onTextLayout={reportLines('inlineView')}>
805+
{'The quick brown '}
806+
<View style={{width: 10, height: 10}} />
807+
{' fox jumps over the lazy dog again and again'}
808+
</Text>
809+
<Text numberOfLines={1} onTextLayout={reportLines('emoji')}>
810+
{'\u{1F600}\u{1F600}\u{1F600} and more text after them'}
811+
</Text>
812+
<Text numberOfLines={2} onTextLayout={reportLines('blankLine')}>
813+
{'Title\n\nMore details'}
814+
</Text>
815+
<Text numberOfLines={2} onTextLayout={reportLines('fittingLines')}>
816+
{'Title\nMore'}
817+
</Text>
818+
<Text
819+
numberOfLines={2}
820+
onTextLayout={reportLines('trailingSpaces')}>
821+
{`Title\nMore${' '.repeat(100)}\n`}
822+
</Text>
823+
<Text numberOfLines={1} onTextLayout={reportLines('clippedView')}>
824+
{'Title\n'}
825+
<View style={{width: 10, height: 10}} />
826+
</Text>
827+
</View>,
828+
);
829+
});
830+
Fantom.flushAllNativeEvents();
831+
832+
expect(linesByText.cut).toHaveLength(2);
833+
expect(linesByText.cut[1].endsWith('\u2026')).toBe(true);
834+
expect(linesByText.fitting).toEqual(['The quick fox']);
835+
// With an inline view or shaped emoji on the last line, the cut stays without an ellipsis.
836+
expect(linesByText.inlineView).toHaveLength(2);
837+
expect(linesByText.inlineView[1].endsWith('\u2026')).toBe(false);
838+
expect(linesByText.emoji).toHaveLength(1);
839+
expect(linesByText.emoji[0].endsWith('\u2026')).toBe(false);
840+
// A blank line cut by a hard break still marks the cut.
841+
expect(linesByText.blankLine).toEqual(['Title', '\u2026']);
842+
// The ellipsis on a blank line has the metrics of its font, like the line above.
843+
expect(blankLineLines[1].capHeight).toBeCloseTo(
844+
blankLineLines[0].capHeight,
845+
);
846+
expect(blankLineLines[1].xHeight).toBeCloseTo(blankLineLines[0].xHeight);
847+
expect(blankLineLines[1].xHeight).toBeGreaterThan(0);
848+
expect(linesByText.fittingLines).toEqual(['Title', 'More']);
849+
// Spaces wrapped before a final line break cut no text.
850+
expect(linesByText.trailingSpaces).toEqual(['Title', 'More']);
851+
// An inline view on a line that was cut away does not stop the ellipsis.
852+
expect(linesByText.clippedView).toEqual(['Title\u2026']);
853+
});
854+
855+
it('draws the ellipsis after a cut emoji in a font that has it', () => {
856+
const renderText = (
857+
root: ReturnType<typeof Fantom.createRoot>,
858+
text: string,
859+
numberOfLines: number,
860+
): ReadonlyArray<string> => {
861+
let reportedLines: ReadonlyArray<string> = [];
862+
Fantom.runTask(() => {
863+
root.render(
864+
<View style={{width: 200, alignItems: 'flex-start'}}>
865+
<Text
866+
numberOfLines={numberOfLines}
867+
onTextLayout={event => {
868+
reportedLines = event.nativeEvent.lines.map(
869+
line => line.text,
870+
);
871+
}}>
872+
{text}
873+
</Text>
874+
</View>,
875+
);
876+
});
877+
Fantom.flushAllNativeEvents();
878+
return reportedLines;
879+
};
880+
881+
const cutRoot = Fantom.createRoot();
882+
const [cutLine] = renderText(
883+
cutRoot,
884+
'Nice \u{1F600}\nmore words after the line break',
885+
1,
886+
);
887+
const typedRoot = Fantom.createRoot();
888+
renderText(typedRoot, 'Nice \u{1F600}\u2026', 1);
889+
890+
expect(cutLine).toBe('Nice \u{1F600}\u2026');
891+
expect(cutRoot.takeScreenshot().isEqual(typedRoot.takeScreenshot())).toBe(
892+
true,
893+
);
894+
});
895+
896+
it('reports the same lines for a cut text that shrinks to fit', () => {
897+
const LONG_TEXT =
898+
'The quick brown fox jumps over the lazy dog again and again';
899+
const cases = Array.from({length: 61}, (_, i) => ({
900+
numberOfLines: 1 + (i % 2),
901+
width: 80 + i,
902+
stretchedLines: [] as Array<string>,
903+
shrunkLines: [] as Array<string>,
904+
}));
905+
const root = Fantom.createRoot();
906+
Fantom.runTask(() => {
907+
root.render(
908+
<>
909+
{cases.map(testCase => (
910+
<React.Fragment key={testCase.width}>
911+
<View style={{width: testCase.width}}>
912+
<Text
913+
numberOfLines={testCase.numberOfLines}
914+
onTextLayout={event => {
915+
testCase.stretchedLines = event.nativeEvent.lines.map(
916+
line => line.text,
917+
);
918+
}}>
919+
{LONG_TEXT}
920+
</Text>
921+
</View>
922+
<View style={{width: testCase.width, alignItems: 'flex-start'}}>
923+
<Text
924+
numberOfLines={testCase.numberOfLines}
925+
onTextLayout={event => {
926+
testCase.shrunkLines = event.nativeEvent.lines.map(
927+
line => line.text,
928+
);
929+
}}>
930+
{LONG_TEXT}
931+
</Text>
932+
</View>
933+
</React.Fragment>
934+
))}
935+
</>,
936+
);
937+
});
938+
Fantom.flushAllNativeEvents();
939+
940+
for (const {numberOfLines, stretchedLines, shrunkLines} of cases) {
941+
expect(stretchedLines).toHaveLength(numberOfLines);
942+
expect(stretchedLines[numberOfLines - 1].endsWith('\u2026')).toBe(true);
943+
expect(shrunkLines).toEqual(stretchedLines);
944+
}
945+
});
946+
});
947+
654948
describe('ref', () => {
655949
it('is a element node', () => {
656950
const elementRef = createRef<HostInstance>();

‎packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,11 @@ TextMeasurement TextLayoutManager::measure(
3636
.attachments = attachments};
3737
}
3838

39+
LinesMeasurements TextLayoutManager::measureLines(
40+
const AttributedStringBox& /*attributedStringBox*/,
41+
const ParagraphAttributes& /*paragraphAttributes*/,
42+
const Size& /*size*/) const {
43+
return {};
44+
}
45+
3946
} // namespace facebook::react

‎packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.h‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,16 @@ class TextLayoutManager {
5151
const TextLayoutContext &layoutContext,
5252
const LayoutConstraints &layoutConstraints) const;
5353

54+
/*
55+
* Measures the lines of `attributedStringBox` laid out at `size`. This
56+
* implementation does not lay text out and returns no lines; a subclass that
57+
* does, such as Fantom's `FantomTextLayoutManager`, overrides it.
58+
*/
59+
virtual LinesMeasurements measureLines(
60+
const AttributedStringBox &attributedStringBox,
61+
const ParagraphAttributes &paragraphAttributes,
62+
const Size &size) const;
63+
5464
protected:
5565
std::shared_ptr<const ContextContainer> contextContainer_;
5666
TextMeasureCache textMeasureCache_;

‎private/react-native-fantom/__docs__/rendering.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,12 @@ without custom path mappings. Keep a fixture alongside the test that uses it.
3333
Default color emoji selection follows Unicode 16.0 `Emoji_Presentation`.
3434
Explicit text and emoji variation selectors override that default. Selectors and
3535
keycap sequences stay with their bases during fallback and wrapping; HarfBuzz
36-
shapes color emoji sequences for both measurement and painting. General script
37-
shaping, text decorations and ellipsis are not implemented.
36+
shapes color emoji sequences for both measurement and painting. With the default
37+
`ellipsizeMode` (`tail`), text cut by `numberOfLines` ends with a tail ellipsis,
38+
except when its last visible line has an inline view or shaped emoji, or when
39+
only spaces were cut. A trailing line break adds no empty last line. General
40+
script shaping, text decorations and head or middle ellipsis are not
41+
implemented.
3842

3943
### Public native build
4044

‎private/react-native-fantom/src/__tests__/__snapshots__/FantomScreenSnapshots-itest.js.snap‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Object {
99

1010
exports[`Fantom screen snapshots captures the feed and its scrolled viewport 1`] = `
1111
Object {
12-
"hash": "a71fd606e25d99e9afc33d276138ae2db1d42352ec0995d23bdaefab811eba17",
12+
"hash": "16b6dd92373af0ffaa0b670193ed834214e9c14f21d5b3cf693138e977141112",
1313
"type": "Screenshot",
1414
}
1515
`;

‎private/react-native-fantom/tester/src/render/ImageRenderer.cpp‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <react/renderer/components/image/ImageProps.h>
2323
#include <react/renderer/components/image/ImageState.h>
2424
#include <react/renderer/components/scrollview/ScrollViewState.h>
25+
#include <react/renderer/components/text/ParagraphProps.h>
2526
#include <react/renderer/components/text/ParagraphState.h>
2627
#include <react/renderer/core/ConcreteState.h>
2728
#include <algorithm>
@@ -314,7 +315,7 @@ void paintView(
314315
}
315316

316317
const std::string_view name(view.componentName ? view.componentName : "");
317-
if (name == "Paragraph" && view.state) {
318+
if ((name == "Paragraph" || name == "SelectableParagraph") && view.state) {
318319
const auto& state =
319320
static_cast<const ConcreteState<ParagraphState>&>(*view.state)
320321
.getData();
@@ -327,7 +328,9 @@ void paintView(
327328
layoutText(
328329
&canvas,
329330
state.attributedString,
330-
state.paragraphAttributes,
331+
// As on iOS, from the props: the state keeps the attributes it was
332+
// created with when only they change.
333+
static_cast<const ParagraphProps&>(*view.props).paragraphAttributes,
331334
frame.size.width),
332335
frame.size.width);
333336
canvas.restore();

0 commit comments

Comments
 (0)