From b62957a17d6aeea0984a56e0b2beac98d0c507aa Mon Sep 17 00:00:00 2001 From: Mark Verlingieri Date: Tue, 1 Dec 2026 15:58:43 -0800 Subject: [PATCH] Add getTextLayout() to Text refs (#60414) Summary: `onTextLayout` reaches JS after the first frame with the text is drawn, so output that depends on a text's lines shows unadjusted for a few frames. This adds `getTextLayout()` to refs of a `` not nested in another ``. It synchronously returns `{lines}`, the same shape and lines as the `onTextLayout` event, so a layout effect can use them in the same commit. - `ParagraphShadowNode` keeps the lines it measures for `onTextLayout` and exposes them through `TextLayoutLinesProvider`, a header-only interface. - `dom::getTextLayoutLines` reads them through that interface; `NativeDOM.getTextLayout` resolves the revision and builds the `{lines}` object. - `Text` adds the method before the ref receives the instance, only when a ref is passed; nested texts don't get it. Changelog: [General][Added] - Add `getTextLayout()` to `` refs Reviewed By: rubennorte Differential Revision: D134142257 --- packages/react-native/Libraries/Text/Text.js | 101 +++- .../Libraries/Text/__tests__/Text-itest.js | 458 +++++++++++++++++- .../react/nativemodule/dom/NativeDOM.cpp | 41 ++ .../react/nativemodule/dom/NativeDOM.h | 2 + .../components/text/ParagraphShadowNode.cpp | 10 +- .../components/text/ParagraphShadowNode.h | 16 +- .../components/text/TextLayoutLinesProvider.h | 33 ++ .../ReactCommon/react/renderer/dom/DOM.cpp | 12 + .../ReactCommon/react/renderer/dom/DOM.h | 9 + packages/react-native/ReactNativeApi.d.ts | 18 +- packages/react-native/__typetests__/index.tsx | 7 + .../webapis/dom/nodes/specs/NativeDOM.js | 15 + .../types_DEPRECATED/Libraries/Text/Text.d.ts | 19 +- .../ReactAndroidFrameworksCxx.api | 9 +- .../api-snapshots/ReactAppleFrameworksCxx.api | 9 +- .../ReactCommonFrameworksCxx.api | 9 +- 16 files changed, 747 insertions(+), 21 deletions(-) create mode 100644 packages/react-native/ReactCommon/react/renderer/components/text/TextLayoutLinesProvider.h diff --git a/packages/react-native/Libraries/Text/Text.js b/packages/react-native/Libraries/Text/Text.js index a5ed1a1bb777..bdcec03574e8 100644 --- a/packages/react-native/Libraries/Text/Text.js +++ b/packages/react-native/Libraries/Text/Text.js @@ -11,11 +11,16 @@ import type {HostInstance} from '../../src/private/types/HostInstance'; import type {TextStyleProp} from '../StyleSheet/StyleSheet'; import type {TextStyle} from '../StyleSheet/StyleSheetTypes'; -import type {GestureResponderEvent} from '../Types/CoreEventTypes'; +import type { + GestureResponderEvent, + TextLayoutLine, +} from '../Types/CoreEventTypes'; import type {NativeTextProps} from './TextNativeComponent'; import type {PressRetentionOffset, TextProps} from './TextProps'; import * as ReactNativeFeatureFlags from '../../src/private/featureflags/ReactNativeFeatureFlags'; +import {getNativeElementReference} from '../../src/private/webapis/dom/nodes/internals/NodeInternals'; +import NativeDOM from '../../src/private/webapis/dom/nodes/specs/NativeDOM'; import * as PressabilityDebug from '../Pressability/PressabilityDebug'; import usePressability from '../Pressability/usePressability'; import flattenStyle from '../StyleSheet/flattenStyle'; @@ -31,7 +36,30 @@ import { import * as React from 'react'; import {useContext, useMemo, useState} from 'react'; -export type TextInstance = HostInstance; +/** + * The methods `Text` adds to the instance of a `` that is not nested in + * another ``. + */ +interface TextInstanceMethods { + /** + * The text's last layout, read synchronously (for example in a layout + * effect), so it is available before the `onTextLayout` event. It has the + * shape of that event's `nativeEvent`: `lines` holds the lines + * `onTextLayout` reports for that layout, with the same platform-specific + * `text`: it need not equal the painted text, and a truncated line does not + * end with an ellipsis on every platform. The text needs an `onTextLayout` + * handler; otherwise, and while new content has not been laid out (for + * example while the text is hidden), `lines` is empty. + * + * Only the instance of a `` that is not nested in another ``, + * and is passed a `ref`, has this method. + */ + getTextLayout?: () => TextLayout; +} + +type TextLayout = Readonly<{lines: ReadonlyArray}>; + +export type TextInstance = HostInstance & TextInstanceMethods; export type {TextProps} from './TextProps'; @@ -292,7 +320,7 @@ const TextImpl: component( if (isPressable) { nativeText = ( + ) : ( - + ); } @@ -337,6 +368,66 @@ const TextImpl: component( TextImpl.displayName = 'Text'; +function getTextLayout(this: HostInstance): TextLayout { + const node = getNativeElementReference(this); + if (node == null || NativeDOM == null || NativeDOM.getTextLayout == null) { + return {lines: []}; + } + return NativeDOM.getTextLayout(node); +} + +function addTextInstanceMethods(instance: TextInstance): void { + // $FlowFixMe[incompatible-use] - Text adds this method to its host instance. + instance.getTextLayout = getTextLayout; +} + +// One ref per forwarded ref, kept across renders, so a `` without a ref +// does no work for it. +const textRefs: WeakMap< + NonNullable>, + (instance: TextInstance | null) => () => void, +> = new WeakMap(); + +/** + * The ref for a `` that is not nested in another ``: it adds the + * instance methods before the forwarded ref gets the instance. + */ +function getTextRef( + forwardedRef: ?React.RefSetter, +): ?React.RefSetter { + if (forwardedRef == null) { + return undefined; + } + let textRef = textRefs.get(forwardedRef); + if (textRef == null) { + textRef = createTextRef(forwardedRef); + textRefs.set(forwardedRef, textRef); + } + return textRef; +} + +function createTextRef( + forwardedRef: NonNullable>, +): (instance: TextInstance | null) => () => void { + return instance => { + if (instance != null) { + addTextInstanceMethods(instance); + } + if (typeof forwardedRef === 'function') { + const cleanup = forwardedRef(instance); + return typeof cleanup === 'function' + ? cleanup + : () => { + forwardedRef(null); + }; + } + forwardedRef.current = instance; + return () => { + forwardedRef.current = null; + }; + }; +} + type TextPressabilityProps = Readonly<{ onLongPress?: ?(event: GestureResponderEvent) => unknown, onPress?: ?(event: GestureResponderEvent) => unknown, diff --git a/packages/react-native/Libraries/Text/__tests__/Text-itest.js b/packages/react-native/Libraries/Text/__tests__/Text-itest.js index 890e3cdc1d55..35d9c4c368a8 100644 --- a/packages/react-native/Libraries/Text/__tests__/Text-itest.js +++ b/packages/react-native/Libraries/Text/__tests__/Text-itest.js @@ -10,8 +10,13 @@ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; +import type {TextLayoutLine} from '../../Types/CoreEventTypes'; import type {HostInstance} from 'react-native'; -import type {AccessibilityProps, TextLayoutEvent} from 'react-native'; +import type { + AccessibilityProps, + TextInstance, + TextLayoutEvent, +} from 'react-native'; import accessibilityPropsSuite, { rolePropSuite, @@ -21,7 +26,7 @@ import ensureInstance from '../../../src/private/__tests__/utilities/ensureInsta import * as Fantom from '@react-native/fantom'; import nullthrows from 'nullthrows'; import * as React from 'react'; -import {createRef} from 'react'; +import {createRef, useEffect, useLayoutEffect, useRef, useState} from 'react'; import {Text, View} from 'react-native'; const TEST_TEXT = 'the text'; @@ -1006,6 +1011,455 @@ describe('', () => { }); }); + describe('getTextLayout', () => { + const LONG_TEXT = + 'The quick brown fox jumps over the lazy dog again and again'; + const ignoreTextLayout = () => {}; + + function readLines(instance: ?TextInstance): ReadonlyArray { + return nullthrows(nullthrows(instance).getTextLayout?.()).lines; + } + + it('returns the lines `onTextLayout` reports, already in the layout effect of the commit', () => { + let linesFromEvent: ?ReadonlyArray = null; + let layoutInLayoutEffect: ?{...} = null; + let linesInLayoutEffect: ?ReadonlyArray = null; + let linesInEffect: ?ReadonlyArray = null; + let eventBeforeLayoutEffect = false; + component TextWithLines() { + const textRef = useRef(null); + useLayoutEffect(() => { + eventBeforeLayoutEffect = linesFromEvent != null; + layoutInLayoutEffect = nullthrows(textRef.current).getTextLayout?.(); + linesInLayoutEffect = readLines(textRef.current); + }); + useEffect(() => { + linesInEffect = readLines(textRef.current); + }); + return ( + + { + linesFromEvent = event.nativeEvent.lines; + }} + ref={textRef}> + {LONG_TEXT} + + + ); + } + + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + Fantom.flushAllNativeEvents(); + + expect(eventBeforeLayoutEffect).toBe(false); + expect(nullthrows(linesInLayoutEffect).length).toBeGreaterThan(1); + expect(linesInLayoutEffect).toEqual(linesFromEvent); + expect(linesInEffect).toEqual(linesFromEvent); + expect(Object.keys(nullthrows(layoutInLayoutEffect))).toEqual(['lines']); + const [firstLine] = nullthrows(linesInLayoutEffect); + expect(Object.keys(firstLine).sort()).toEqual([ + 'ascender', + 'capHeight', + 'descender', + 'height', + 'text', + 'width', + 'x', + 'xHeight', + 'y', + ]); + }); + + it('returns the lines in the first callback ref of a new text', () => { + let linesInRef: ?ReadonlyArray = null; + let linesFromEvent: ?ReadonlyArray = null; + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render( + + { + linesFromEvent = event.nativeEvent.lines; + }} + ref={instance => { + if (instance != null && linesInRef == null) { + linesInRef = readLines(instance); + } + }}> + {LONG_TEXT} + + , + ); + }); + expect(linesFromEvent).toBe(null); + Fantom.flushAllNativeEvents(); + + expect(nullthrows(linesInRef).length).toBeGreaterThan(1); + expect(linesInRef).toEqual(linesFromEvent); + }); + + it('mounts a correction made from the lines in the same task as the text', () => { + component LineReader(readInLayoutEffect: boolean) { + const textRef = useRef(null); + const [hasRead, setHasRead] = useState(false); + useLayoutEffect(() => { + if (readInLayoutEffect) { + setHasRead(readLines(textRef.current).length > 1); + } + }, [readInLayoutEffect]); + return ( + + { + setHasRead(event.nativeEvent.lines.length > 1); + }} + ref={textRef}> + {LONG_TEXT} + + + + ); + } + const mountedNativeIDs = (readInLayoutEffect: boolean) => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + const logs = root.takeMountingManagerLogs().join('\n'); + Fantom.flushAllNativeEvents(); + const logsAfterEvents = root.takeMountingManagerLogs().join('\n'); + return [logs, logsAfterEvents].map(taskLogs => + ['lines-read', 'lines-unread'].filter(id => taskLogs.includes(id)), + ); + }; + + expect(mountedNativeIDs(true)).toEqual([['lines-read'], []]); + expect(mountedNativeIDs(false)).toEqual([ + ['lines-unread'], + ['lines-read'], + ]); + }); + + it('returns the lines of the latest layout', () => { + const textRef = createRef(); + let linesFromEvent: ?ReadonlyArray = null; + const root = Fantom.createRoot(); + const renderAtWidth = (width: number) => { + Fantom.runTask(() => { + root.render( + + { + linesFromEvent = event.nativeEvent.lines; + }} + ref={textRef}> + {LONG_TEXT} + + , + ); + }); + Fantom.flushAllNativeEvents(); + }; + + renderAtWidth(100); + const narrowLines = readLines(textRef.current); + renderAtWidth(1000); + const wideLines = readLines(textRef.current); + + expect(wideLines).toEqual(linesFromEvent); + expect(wideLines.length).toBeLessThan(narrowLines.length); + }); + + it('returns no lines once `onTextLayout` is removed', () => { + const textRef = createRef(); + const root = Fantom.createRoot(); + const renderText = (onTextLayout: ?() => void) => { + Fantom.runTask(() => { + root.render( + + + {LONG_TEXT} + + , + ); + }); + }; + + renderText(() => {}); + expect(readLines(textRef.current).length).toBeGreaterThan(1); + + renderText(null); + expect(readLines(textRef.current)).toEqual([]); + }); + + it('returns the lines kept from the last layout when only a sibling changes', () => { + const textRef = createRef(); + const root = Fantom.createRoot(); + const renderWithSibling = (siblingWidth: number) => { + Fantom.runTask(() => { + root.render( + + + {LONG_TEXT} + + + , + ); + }); + }; + + renderWithSibling(10); + const linesBefore = readLines(textRef.current); + renderWithSibling(20); + + expect(linesBefore.length).toBeGreaterThan(1); + expect(readLines(textRef.current)).toEqual(linesBefore); + }); + + it('returns the new lines in the layout effect of a visible text update', () => { + const textRef = createRef(); + const root = Fantom.createRoot(); + const linesRead: Array> = []; + component TextWithReader(text: string) { + useLayoutEffect(() => { + linesRead.push(readLines(textRef.current).map(line => line.text)); + }, [text]); + return ( + + + {text} + + + ); + } + + Fantom.runTask(() => { + root.render(); + }); + Fantom.runTask(() => { + root.render(); + }); + + expect(linesRead[0]).toEqual(['Short']); + expect(linesRead[1].length).toBeGreaterThan(1); + expect(linesRead[1].join('')).toContain('lazy dog'); + }); + + it('returns one empty line when a mounted text becomes empty', () => { + const textRef = createRef(); + let linesFromEvent: ?ReadonlyArray = null; + const onTextLayout = (event: TextLayoutEvent) => { + linesFromEvent = event.nativeEvent.lines; + }; + const root = Fantom.createRoot(); + const renderText = (text: string) => { + Fantom.runTask(() => { + root.render( + + + {text} + + , + ); + }); + Fantom.flushAllNativeEvents(); + }; + + renderText('Short'); + expect(readLines(textRef.current)).toEqual(linesFromEvent); + + renderText(''); + expect(readLines(textRef.current).map(line => line.text)).toEqual(['']); + expect(readLines(textRef.current)).toEqual(linesFromEvent); + }); + + it('returns no lines for text changed while hidden, and its lines once shown', () => { + const textRef = createRef(); + let linesFromEvent: ?ReadonlyArray = null; + const onTextLayout = (event: TextLayoutEvent) => { + linesFromEvent = event.nativeEvent.lines; + }; + const root = Fantom.createRoot(); + const renderText = (text: string, hidden: boolean) => { + Fantom.runTask(() => { + root.render( + , + ); + }); + Fantom.flushAllNativeEvents(); + }; + + renderText(LONG_TEXT, false); + expect(readLines(textRef.current).length).toBeGreaterThan(1); + + renderText(`${LONG_TEXT} and once more`, true); + expect(readLines(textRef.current)).toEqual([]); + + renderText(`${LONG_TEXT} and once more`, false); + const shownLines = readLines(textRef.current); + expect(shownLines.map(line => line.text).join('')).toContain('once more'); + expect(shownLines).toEqual(linesFromEvent); + }); + + it('returns no lines for a text without `onTextLayout`', () => { + const textRef = createRef(); + const measuredTextRef = createRef(); + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render( + + {LONG_TEXT} + + {LONG_TEXT} + + , + ); + }); + + expect(readLines(textRef.current)).toEqual([]); + expect(readLines(measuredTextRef.current).length).toBeGreaterThan(1); + }); + + it('is on the instance of a pressable or selectable text', () => { + const pressableRef = createRef(); + const selectableRef = createRef(); + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render( + + {}} + onTextLayout={ignoreTextLayout} + ref={pressableRef}> + {LONG_TEXT} + + + {LONG_TEXT} + + , + ); + }); + + expect(readLines(pressableRef.current).length).toBeGreaterThan(1); + expect(readLines(selectableRef.current).length).toBeGreaterThan(1); + }); + + it('is not on the instance of a nested text or of another component', () => { + const outerRef = createRef(); + const nestedRef = createRef(); + const pressableNestedRef = createRef(); + const viewRef = createRef(); + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render( + + + nested + {}} ref={pressableNestedRef}> + pressable + + + , + ); + }); + + expect(readLines(outerRef.current).length).toBeGreaterThan(0); + expect(nullthrows(nestedRef.current).getTextLayout).toBeUndefined(); + expect( + nullthrows(pressableNestedRef.current).getTextLayout, + ).toBeUndefined(); + expect('getTextLayout' in nullthrows(viewRef.current)).toBe(false); + }); + + it('clears or cleans up each kind of forwarded ref on unmount', () => { + const objectRef = createRef(); + const callbackRefValues: Array = []; + const cleanupRefValues: Array = []; + let cleanups = 0; + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render( + + + {LONG_TEXT} + + { + callbackRefValues.push(instance); + }}> + {LONG_TEXT} + + { + cleanupRefValues.push(instance); + return () => { + cleanups++; + }; + }}> + {LONG_TEXT} + + , + ); + }); + + expect(readLines(objectRef.current).length).toBeGreaterThan(1); + expect(readLines(callbackRefValues[0]).length).toBeGreaterThan(1); + expect(readLines(cleanupRefValues[0]).length).toBeGreaterThan(1); + + Fantom.runTask(() => { + root.render(); + }); + + expect(objectRef.current).toBe(null); + expect(callbackRefValues).toHaveLength(2); + expect(callbackRefValues[1]).toBe(null); + expect(cleanupRefValues).toHaveLength(1); + expect(cleanups).toBe(1); + }); + + it('stays on the instance when its ref changes', () => { + const instances: Array = []; + const root = Fantom.createRoot(); + const renderText = () => { + Fantom.runTask(() => { + root.render( + + { + if (instance != null) { + instances.push(instance); + } + }}> + {LONG_TEXT} + + , + ); + }); + }; + + renderText(); + renderText(); + + expect(instances).toHaveLength(2); + expect(instances[1]).toBe(instances[0]); + expect(readLines(instances[1]).length).toBeGreaterThan(1); + }); + }); + describe('displayName', () => { it('is "Text"', () => { expect(Text.displayName).toBe('Text'); diff --git a/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.cpp b/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.cpp index 3a24d57807e3..8ec646822105 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.cpp @@ -87,6 +87,31 @@ bool isRootShadowNode(const ShadowNode& shadowNode) { return shadowNode.getTraits().check(ShadowNodeTraits::Trait::RootNodeKind); } +// The shape of the `textLayout` event's payload: an object with a `lines` +// array. +jsi::Object textLayoutToJSI( + jsi::Runtime& rt, + const LinesMeasurements& linesMeasurements) { + auto lines = jsi::Array(rt, linesMeasurements.size()); + for (size_t i = 0; i < linesMeasurements.size(); ++i) { + const auto& lineMeasurement = linesMeasurements[i]; + auto line = jsi::Object(rt); + line.setProperty(rt, "text", lineMeasurement.text); + line.setProperty(rt, "x", lineMeasurement.frame.origin.x); + line.setProperty(rt, "y", lineMeasurement.frame.origin.y); + line.setProperty(rt, "width", lineMeasurement.frame.size.width); + line.setProperty(rt, "height", lineMeasurement.frame.size.height); + line.setProperty(rt, "descender", lineMeasurement.descender); + line.setProperty(rt, "capHeight", lineMeasurement.capHeight); + line.setProperty(rt, "ascender", lineMeasurement.ascender); + line.setProperty(rt, "xHeight", lineMeasurement.xHeight); + lines.setValueAtIndex(rt, i, line); + } + auto textLayout = jsi::Object(rt); + textLayout.setProperty(rt, "lines", lines); + return textLayout; +} + } // namespace #pragma mark - NativeDOM @@ -341,6 +366,22 @@ std::string NativeDOM::getTextContent( return dom::getTextContent(currentRevision, *shadowNode); } +jsi::Value NativeDOM::getTextLayout( + jsi::Runtime& rt, + std::shared_ptr shadowNode) { + auto currentRevision = + getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); + if (currentRevision == nullptr) { + return textLayoutToJSI(rt, {}); + } + auto linesMeasurements = + dom::getTextLayoutLines(currentRevision, *shadowNode); + if (linesMeasurements == nullptr) { + return textLayoutToJSI(rt, {}); + } + return textLayoutToJSI(rt, *linesMeasurements); +} + bool NativeDOM::hasPointerCapture( jsi::Runtime& rt, std::shared_ptr shadowNode, diff --git a/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h b/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h index c3a3c6e6c38e..8aeaddf29353 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h +++ b/packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h @@ -76,6 +76,8 @@ class NativeDOM : public NativeDOMCxxSpec { std::string getTextContent(jsi::Runtime &rt, std::shared_ptr shadowNode); + jsi::Value getTextLayout(jsi::Runtime &rt, std::shared_ptr shadowNode); + bool hasPointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); void releasePointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp index 910d73f39460..3a9bbbde6fcf 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp @@ -91,6 +91,10 @@ ParagraphShadowNode::ParagraphShadowNode( if (fragment.props == nullptr && fragment.children == nullptr) { const auto& source = static_cast(sourceShadowNode); + // The lines measured for the source describe the same content. A clone + // with new props or children waits for its own layout, which a hidden + // paragraph never gets. + linesMeasurements_ = source.linesMeasurements_; if (source.content_.has_value() && source.content_->attachments.empty()) { content_ = source.content_; // A layout is later matched by its measured size alone (see @@ -474,11 +478,11 @@ void ParagraphShadowNode::layout(LayoutContext layoutContext) { if (getConcreteProps().onTextLayout) { if constexpr (TextLayoutManagerExtended::supportsLineMeasurement()) { - auto linesMeasurements = + linesMeasurements_ = std::make_shared( TextLayoutManagerExtended(*textLayoutManager_) .measureLines( - attributedStringBox, content.paragraphAttributes, size); - getConcreteEventEmitter().onTextLayout(linesMeasurements); + attributedStringBox, content.paragraphAttributes, size)); + getConcreteEventEmitter().onTextLayout(*linesMeasurements_); } else { LOG(WARNING) << "onTextLayout is not supported by the current platform"; } diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h index 7c5efc534df5..b67bd50118fa 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -29,7 +30,8 @@ extern const char ParagraphComponentName[]; */ class ParagraphShadowNode : public ConcreteViewShadowNode, - public BaseTextShadowNode { + public BaseTextShadowNode, + public TextLayoutLinesProvider { public: using ConcreteViewShadowNode::ConcreteViewShadowNode; @@ -57,6 +59,16 @@ class ParagraphShadowNode Float baseline(const LayoutContext &layoutContext, Size size) const override; + /* + * The lines of the last layout, measured when the paragraph has an + * `onTextLayout` handler. Null otherwise, and in a revision with new props + * or children until it is laid out. + */ + std::shared_ptr getLinesMeasurements() const override + { + return linesMeasurements_; + } + /* * Internal representation of the nested content of the node in a format * suitable for future processing. @@ -134,6 +146,8 @@ class ParagraphShadowNode * JNI global reference). */ mutable std::vector> measuredLayouts_; + + std::shared_ptr linesMeasurements_; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/TextLayoutLinesProvider.h b/packages/react-native/ReactCommon/react/renderer/components/text/TextLayoutLinesProvider.h new file mode 100644 index 000000000000..4625b9c0e538 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/components/text/TextLayoutLinesProvider.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include + +#include + +namespace facebook::react { + +/* + * A shadow node that keeps the lines of its last layout. Header-only and free + * of platform headers, so the DOM APIs can read the lines without depending on + * the text component. + */ +class TextLayoutLinesProvider { + public: + virtual ~TextLayoutLinesProvider() = default; + + /* + * The lines of the last layout, or null when none were kept. + */ + virtual std::shared_ptr getLinesMeasurements() const = 0; +}; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/dom/DOM.cpp b/packages/react-native/ReactCommon/react/renderer/dom/DOM.cpp index 0cec80aaec44..e25b9e44d9cd 100644 --- a/packages/react-native/ReactCommon/react/renderer/dom/DOM.cpp +++ b/packages/react-native/ReactCommon/react/renderer/dom/DOM.cpp @@ -7,6 +7,7 @@ #include "DOM.h" #include +#include #include #include #include @@ -270,6 +271,17 @@ std::string getTextContent( return result; } +std::shared_ptr getTextLayoutLines( + const RootShadowNode::Shared& currentRevision, + const ShadowNode& shadowNode) { + auto provider = std::dynamic_pointer_cast( + getShadowNodeInRevision(currentRevision, shadowNode)); + if (provider == nullptr) { + return nullptr; + } + return provider->getLinesMeasurements(); +} + DOMRect getBoundingClientRect( const RootShadowNode::Shared& currentRevision, const ShadowNode& shadowNode, diff --git a/packages/react-native/ReactCommon/react/renderer/dom/DOM.h b/packages/react-native/ReactCommon/react/renderer/dom/DOM.h index 1f87f39aa0f1..8d73882cf92f 100644 --- a/packages/react-native/ReactCommon/react/renderer/dom/DOM.h +++ b/packages/react-native/ReactCommon/react/renderer/dom/DOM.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -83,6 +84,14 @@ uint_fast16_t compareDocumentPosition( std::string getTextContent(const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode); +/* + * The lines a paragraph kept from its last layout for `onTextLayout`. Null when + * the node is not a paragraph in the current revision or kept no lines. + */ +std::shared_ptr getTextLayoutLines( + const RootShadowNode::Shared ¤tRevision, + const ShadowNode &shadowNode); + DOMRect getBoundingClientRect( const RootShadowNode::Shared ¤tRevision, const ShadowNode &shadowNode, diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index b4ff97b432f9..735254dac1c8 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<83cb6ada8f8cb7c30a4c47d44d892dca>> + * @generated SignedSource<> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -5272,7 +5272,13 @@ declare type TextInputSubmitEditingEventData = Readonly< } > declare type TextInputType = InternalTextInput & TextInputComponentStatics -declare type TextInstance = HostInstance +declare type TextInstance = HostInstance & TextInstanceMethods +declare interface TextInstanceMethods { + getTextLayout?: () => TextLayout +} +declare type TextLayout = { + readonly lines: ReadonlyArray +} declare type TextLayoutEvent = NativeSyntheticEvent declare type TextLayoutEventData = { readonly lines: Array @@ -5902,12 +5908,12 @@ export { AlertOptions, // 8a116d2a AlertType, // 5ab91217 AndroidKeyboardEvent, // e03becc8 - Animated, // 7e828987 + Animated, // 633f77ed AnimatedFlatList, // f32979ff AnimatedImage, // 08521177 AnimatedScrollView, // 1b410f55 AnimatedSectionList, // 8614a499 - AnimatedText, // 206f1fc7 + AnimatedText, // 3b505d7f AnimatedView, // 544c0f25 AppConfig, // 80afc5fa AppRegistry, // 41af4d77 @@ -6143,7 +6149,7 @@ export { TVViewPropsIOS, // 1c612e4e TargetedEvent, // 16e98910 TaskProvider, // 266dedf2 - Text, // 9b0ab4e8 + Text, // 9b909b32 TextContentType, // 239b3ecc TextInput, // 049f725c TextInputAndroidProps, // 9ebbc103 @@ -6158,7 +6164,7 @@ export { TextInputProps, // b119ebb7 TextInputSelectionChangeEvent, // 817bea8a TextInputSubmitEditingEvent, // 260f6e41 - TextInstance, // c927e793 + TextInstance, // 94995d3e TextLayoutEvent, // e9765128 TextProps, // 657544ac TextStyle, // c7ab3ab7 diff --git a/packages/react-native/__typetests__/index.tsx b/packages/react-native/__typetests__/index.tsx index 75e5dce1634c..dab4b91c8efd 100644 --- a/packages/react-native/__typetests__/index.tsx +++ b/packages/react-native/__typetests__/index.tsx @@ -446,6 +446,13 @@ class Welcome extends React.Component< } } + testTextLayout(textRef: React.ComponentRef | null) { + const lines = textRef?.getTextLayout?.().lines ?? []; + const texts: ReadonlyArray = lines.map(line => line.text); + const widths: ReadonlyArray = lines.map(line => line.width); + return [texts, widths]; + } + testFindNodeHandle() { if (this.rootViewRef.current != null) { const nativeComponentHandle = findNodeHandle(this.rootViewRef.current); diff --git a/packages/react-native/src/private/webapis/dom/nodes/specs/NativeDOM.js b/packages/react-native/src/private/webapis/dom/nodes/specs/NativeDOM.js index 5253243ef670..4b70187b6ec7 100644 --- a/packages/react-native/src/private/webapis/dom/nodes/specs/NativeDOM.js +++ b/packages/react-native/src/private/webapis/dom/nodes/specs/NativeDOM.js @@ -11,6 +11,7 @@ import type {RootTag} from '../../../../../../Libraries/ReactNative/RootTag'; import type {Node as ShadowNode} from '../../../../../../Libraries/Renderer/shims/ReactNativeTypes'; import type {TurboModule} from '../../../../../../Libraries/TurboModule/RCTExport'; +import type {TextLayoutLine} from '../../../../../../Libraries/Types/CoreEventTypes'; import type {InstanceHandle} from '../internals/NodeInternals'; import * as TurboModuleRegistry from '../../../../../../Libraries/TurboModule/TurboModuleRegistry'; @@ -104,6 +105,10 @@ export interface Spec extends TurboModule { nativeElementReference: unknown /* NativeElementReference */, ) => string; + readonly getTextLayout?: ( + nativeElementReference: unknown /* NativeElementReference */, + ) => unknown; /* {lines: ReadonlyArray} */ + readonly hasPointerCapture: ( nativeElementReference: unknown /* NativeElementReference */, pointerId: number, @@ -348,6 +353,16 @@ export interface RefinedSpec { */ readonly getTextContent: (nativeNodeReference: NativeNodeReference) => string; + /** + * A paragraph's last layout, read synchronously, in the shape of the + * `onTextLayout` event's `nativeEvent`: `{lines}`. Only paragraphs with an + * `onTextLayout` handler measure their lines. `lines` is empty for anything + * else, and while new content has not been laid out. + */ + readonly getTextLayout?: ( + nativeElementReference: NativeElementReference, + ) => Readonly<{lines: ReadonlyArray}>; + readonly hasPointerCapture: ( nativeElementReference: NativeElementReference, pointerId: number, diff --git a/packages/react-native/types_DEPRECATED/Libraries/Text/Text.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Text/Text.d.ts index e793c03bc6d5..f0f619141fee 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Text/Text.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Text/Text.d.ts @@ -225,6 +225,23 @@ export interface TextProps */ declare class TextComponent extends React.Component {} declare const TextBase: Constructor & typeof TextComponent; -export class Text extends TextBase {} +export class Text extends TextBase { + /** + * The text's last layout, read synchronously (for example in a layout + * effect), so it is available before the `onTextLayout` event. It has the + * shape of that event's `nativeEvent`: `lines` holds the lines `onTextLayout` + * reports for that layout. The text needs an `onTextLayout` handler; + * otherwise, and while new content has not been laid out (for example while + * the text is hidden), `lines` is empty. + * + * Only the instance of a `` that is not nested in another ``, + * and is passed a `ref`, has this method. + */ + getTextLayout?(): { + readonly lines: ReadonlyArray< + TextLayoutEvent['nativeEvent']['lines'][number] + >; + }; +} export const unstable_TextAncestorContext: React.Context; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api index f1811b25c34a..3c35ec2ee54e 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api @@ -3167,13 +3167,14 @@ class facebook::react::ParagraphEventEmitter : public facebook::react::BaseViewE public void onTextLayout(const facebook::react::LinesMeasurements& linesMeasurements) const; } -class facebook::react::ParagraphShadowNode : public facebook::react::ConcreteViewShadowNode, public facebook::react::BaseTextShadowNode { +class facebook::react::ParagraphShadowNode : public facebook::react::ConcreteViewShadowNode, public facebook::react::BaseTextShadowNode, public facebook::react::TextLayoutLinesProvider { protected virtual bool shouldNewRevisionDirtyMeasurement(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment) const override; public ParagraphShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ParagraphShadowNode(const facebook::react::ShadowNodeFragment& fragment, const facebook::react::ShadowNodeFamily::Shared& family, facebook::react::ShadowNodeTraits traits); public static facebook::react::ShadowNodeTraits BaseTraits(); public virtual facebook::react::Float baseline(const facebook::react::LayoutContext& layoutContext, facebook::react::Size size) const override; public virtual facebook::react::Size measureContent(const facebook::react::LayoutContext& layoutContext, const facebook::react::LayoutConstraints& layoutConstraints) const override; + public virtual std::shared_ptr getLinesMeasurements() const override; public virtual void layout(facebook::react::LayoutContext layoutContext) override; public void setTextLayoutManager(std::shared_ptr textLayoutManager); } @@ -4017,6 +4018,11 @@ class facebook::react::TextInputState { public int64_t mostRecentEventCount; } +class facebook::react::TextLayoutLinesProvider { + public virtual std::shared_ptr getLinesMeasurements() const = 0; + public virtual ~TextLayoutLinesProvider() = default; +} + class facebook::react::TextLayoutManager { public TextLayoutManager(const facebook::react::TextLayoutManager&) = delete; public TextLayoutManager(const std::shared_ptr& contextContainer); @@ -8907,6 +8913,7 @@ facebook::react::dom::DOMSizeRounded facebook::react::dom::getInnerSize(const fa facebook::react::dom::DOMSizeRounded facebook::react::dom::getScrollSize(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); facebook::react::dom::RNMeasureRect facebook::react::dom::measure(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); std::optional facebook::react::dom::measureLayout(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode, const facebook::react::ShadowNode& relativeToShadowNode); +std::shared_ptr facebook::react::dom::getTextLayoutLines(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); std::shared_ptr facebook::react::dom::getElementById(const std::shared_ptr& currentRevision, const std::string& id); std::shared_ptr facebook::react::dom::getParentNode(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); std::string facebook::react::dom::getTagName(const facebook::react::ShadowNode& shadowNode); diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index c191f3f7f57e..b99068078b5b 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -5353,13 +5353,14 @@ class facebook::react::ParagraphEventEmitter : public facebook::react::BaseViewE public void onTextLayout(const facebook::react::LinesMeasurements& linesMeasurements) const; } -class facebook::react::ParagraphShadowNode : public facebook::react::ConcreteViewShadowNode, public facebook::react::BaseTextShadowNode { +class facebook::react::ParagraphShadowNode : public facebook::react::ConcreteViewShadowNode, public facebook::react::BaseTextShadowNode, public facebook::react::TextLayoutLinesProvider { protected virtual bool shouldNewRevisionDirtyMeasurement(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment) const override; public ParagraphShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ParagraphShadowNode(const facebook::react::ShadowNodeFragment& fragment, const facebook::react::ShadowNodeFamily::Shared& family, facebook::react::ShadowNodeTraits traits); public static facebook::react::ShadowNodeTraits BaseTraits(); public virtual facebook::react::Float baseline(const facebook::react::LayoutContext& layoutContext, facebook::react::Size size) const override; public virtual facebook::react::Size measureContent(const facebook::react::LayoutContext& layoutContext, const facebook::react::LayoutConstraints& layoutConstraints) const override; + public virtual std::shared_ptr getLinesMeasurements() const override; public virtual void layout(facebook::react::LayoutContext layoutContext) override; public void setTextLayoutManager(std::shared_ptr textLayoutManager); } @@ -6198,6 +6199,11 @@ class facebook::react::TextInputTraits { public std::vector dataDetectorTypes; } +class facebook::react::TextLayoutLinesProvider { + public virtual std::shared_ptr getLinesMeasurements() const = 0; + public virtual ~TextLayoutLinesProvider() = default; +} + class facebook::react::TextLayoutManager { protected facebook::react::LineMeasureCache lineMeasureCache_; protected facebook::react::TextMeasureCache textMeasureCache_; @@ -10759,6 +10765,7 @@ facebook::react::dom::DOMSizeRounded facebook::react::dom::getInnerSize(const fa facebook::react::dom::DOMSizeRounded facebook::react::dom::getScrollSize(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); facebook::react::dom::RNMeasureRect facebook::react::dom::measure(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); std::optional facebook::react::dom::measureLayout(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode, const facebook::react::ShadowNode& relativeToShadowNode); +std::shared_ptr facebook::react::dom::getTextLayoutLines(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); std::shared_ptr facebook::react::dom::getElementById(const std::shared_ptr& currentRevision, const std::string& id); std::shared_ptr facebook::react::dom::getParentNode(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); std::string facebook::react::dom::getTagName(const facebook::react::ShadowNode& shadowNode); diff --git a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api index e51e5f696060..f5bab50c02f9 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api @@ -1825,13 +1825,14 @@ class facebook::react::ParagraphEventEmitter : public facebook::react::ViewEvent public void onTextLayout(const facebook::react::LinesMeasurements& linesMeasurements) const; } -class facebook::react::ParagraphShadowNode : public facebook::react::ConcreteViewShadowNode, public facebook::react::BaseTextShadowNode { +class facebook::react::ParagraphShadowNode : public facebook::react::ConcreteViewShadowNode, public facebook::react::BaseTextShadowNode, public facebook::react::TextLayoutLinesProvider { protected virtual bool shouldNewRevisionDirtyMeasurement(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment) const override; public ParagraphShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ParagraphShadowNode(const facebook::react::ShadowNodeFragment& fragment, const facebook::react::ShadowNodeFamily::Shared& family, facebook::react::ShadowNodeTraits traits); public static facebook::react::ShadowNodeTraits BaseTraits(); public virtual Float baseline(const facebook::react::LayoutContext& layoutContext, facebook::react::Size size) const override; public virtual facebook::react::Size measureContent(const facebook::react::LayoutContext& layoutContext, const facebook::react::LayoutConstraints& layoutConstraints) const override; + public virtual std::shared_ptr getLinesMeasurements() const override; public virtual void layout(facebook::react::LayoutContext layoutContext) override; public void setTextLayoutManager(std::shared_ptr textLayoutManager); } @@ -2538,6 +2539,11 @@ class facebook::react::TextInputState { public int64_t mostRecentEventCount; } +class facebook::react::TextLayoutLinesProvider { + public virtual std::shared_ptr getLinesMeasurements() const = 0; + public virtual ~TextLayoutLinesProvider() = default; +} + class facebook::react::TextMeasureCacheKey { public Float pointScaleFactor; public facebook::react::AttributedString attributedString; @@ -6093,6 +6099,7 @@ facebook::react::dom::DOMSizeRounded facebook::react::dom::getInnerSize(const fa facebook::react::dom::DOMSizeRounded facebook::react::dom::getScrollSize(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); facebook::react::dom::RNMeasureRect facebook::react::dom::measure(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); std::optional facebook::react::dom::measureLayout(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode, const facebook::react::ShadowNode& relativeToShadowNode); +std::shared_ptr facebook::react::dom::getTextLayoutLines(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); std::shared_ptr facebook::react::dom::getElementById(const std::shared_ptr& currentRevision, const std::string& id); std::shared_ptr facebook::react::dom::getParentNode(const facebook::react::RootShadowNode::Shared& currentRevision, const facebook::react::ShadowNode& shadowNode); std::string facebook::react::dom::getTagName(const facebook::react::ShadowNode& shadowNode);