From 1656394bae16cc54fb38687d38bcbf85138c98a2 Mon Sep 17 00:00:00 2001
From: Qichen Zhu <57348009+QichenZhu@users.noreply.github.com>
Date: Thu, 10 Oct 2024 08:29:56 -0700
Subject: [PATCH] Set TextInput selection correctly when attached to window in
Android (#46948)
Summary:
On Android, when `ReactEditText` is attached to window, `setTextIsSelectable` moves the caret to the beginning, so we need to restore the selection.
This is similar to what we did in https://github.com/facebook/react-native/pull/17851.
Fixes https://github.com/facebook/react-native/issues/46943
## Changelog:
[ANDROID] [FIXED] - Fix TextInput caret moving to the beginning when attached to window
Pull Request resolved: https://github.com/facebook/react-native/pull/46948
Test Plan:
Code to reproduce in RNTester:
```TSX
import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
import {TextInput} from 'react-native';
import {useEffect, useRef} from 'react';
function Playground() {
const input = useRef(null);
useEffect(() => { setTimeout(() => input.current?.focus(), 1000); }, []);
return ;
}
export default ({
title: 'Playground',
name: 'playground',
render: (): React.Node => ,
}: RNTesterModuleExample);
```
Before | After
-- | --
 | 
Reviewed By: cortinico
Differential Revision: D64175774
Pulled By: rshest
fbshipit-source-id: ef9fdbecca582c8075bcdfd2d9b810b04d87e3d9
---
.../com/facebook/react/views/textinput/ReactEditText.java | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java
index 92cd700113c..ed4ab7a4ddf 100644
--- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java
+++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java
@@ -1035,12 +1035,18 @@ public class ReactEditText extends AppCompatEditText {
public void onAttachedToWindow() {
super.onAttachedToWindow();
+ int selectionStart = getSelectionStart();
+ int selectionEnd = getSelectionEnd();
+
// Used to ensure that text is selectable inside of removeClippedSubviews
// See https://github.com/facebook/react-native/issues/6805 for original
// fix that was ported to here.
super.setTextIsSelectable(true);
+ // Restore the selection since `setTextIsSelectable` changed it.
+ setSelection(selectionStart, selectionEnd);
+
if (mContainsImages) {
Spanned text = getText();
TextInlineImageSpan[] spans = text.getSpans(0, text.length(), TextInlineImageSpan.class);