Fix crash when link endOffset > line offset (#51372)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51372

I got notified that a recent change I made was causing a crash. This would happen when the endOffset of the link is larger than the end offset of the line. This can be repro'd with

```
/**
 * (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
 *
 * flow strict-local
 * format
 */

import {useState} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

export default function Playground() {
  const [state, setState] = useState(false);
  function toggle() {
    setState(old => !old);
  }

  return (
    <View style={styles.container}>
      <Text
        style={[styles.paragraph, state && {backgroundColor: 'red'}]}
        numberOfLines={3}>
        <Text>Bacon Ipsum{'\n'}</Text>
        <Text>Dolor sit amet{'\n'}</Text>
        <Text>{'\n'}</Text>
        <Text accessibilityRole="link" onPress={toggle}>
          http://www.google.com
        </Text>
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: 24,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});
```

This was encountered already by NickGerleman in D46206673 (https://github.com/facebook/react-native/pull/37050) and the fix is fairly straightforward. I modified that fix to check for the endOffset as well.

Changelog: [Internal]

Reviewed By: zeyap

Differential Revision: D74823458

fbshipit-source-id: 08fe81893f1c41d1934215515f88a6e0e546e705
This commit is contained in:
Joe Vilches authored and Facebook GitHub Bot committed 2025-05-15 13:39:19 -07:00
1 parent dcf45f73b9
commit 0c6a60e2fe
1 file changed
+4 -3
@@ -224,8 +224,10 @@ internal class ReactTextViewAccessibilityDelegate : ReactAccessibilityDelegate {
// Ensure the link hasn't been ellipsized away; in such cases,
// getPrimaryHorizontal will crash (and the link isn't rendered anyway).
val startOffsetLineNumber = textViewLayout.getLineForOffset(startOffset)
val lineEndOffset = textViewLayout.getLineEnd(startOffsetLineNumber)
if (startOffset > lineEndOffset) {
val startLineEndOffset = textViewLayout.getLineEnd(startOffsetLineNumber)
val endOffsetLineNumber = textViewLayout.getLineForOffset(endOffset)
val endLineEndOffset = textViewLayout.getLineEnd(endOffsetLineNumber)
if (startOffset > startLineEndOffset || endOffset > endLineEndOffset) {
return null
}
@@ -233,7 +235,6 @@ internal class ReactTextViewAccessibilityDelegate : ReactAccessibilityDelegate {
val startXCoordinates = textViewLayout.getPrimaryHorizontal(startOffset).toDouble()
val endOffsetLineNumber = textViewLayout.getLineForOffset(endOffset)
val isMultiline = startOffsetLineNumber != endOffsetLineNumber
textViewLayout.getLineBounds(startOffsetLineNumber, rootRect)