Skip to content

Commit

Permalink
Fix copy / paste menu and simplify controlled text selection on Andro…
Browse files Browse the repository at this point in the history
…id (#37424)

Summary:
Currently when using a TextInput with a controlled selection prop the Copy / Paste menu is constantly getting dismissed and is impossible to use. This is because Android dismisses it when certain method that affect the input text are called (https://cs.android.com/android/platform/superproject/+/refs/heads/master:frameworks/base/core/java/android/widget/Editor.java;l=1667;drc=7346c436e5a11ce08f6a80dcfeb8ef941ca30176?q=Editor, https://cs.android.com/android/platform/superproject/+/refs/heads/master:frameworks/base/core/java/android/widget/TextView.java;l=6792;drc=7346c436e5a11ce08f6a80dcfeb8ef941ca30176). The solution to fix this is to avoid calling those methods when only the selection changes.

I also noticed there are a lot of differences on how selection is handled in old vs new arch and a lot of the selection handling can actually be removed as it is partially the cause of this issue.

This implements 2 mitigations to avoid the issue:

- Unify selection handling via commands for old arch, like fabric. Selection is currently a prop in the native component, but it is completely ignored in fabric and selection is set using commands. I removed the selection prop from the native component on Android so now it is exclusively handled with commands like it is currently for fabric. This makes it so that when the selection prop changes the native component no longer re-renders which helps mitigate this issue. More specifically for the old arch we no longer handle the `selection` prop in `ReactTextInputShadowNode`, which used to invalidate the shadow node and cause the text to be replaced and the copy / paste menu to close.

- Only set placeholder if the text value changed. Calling `EditText.setHint` also causes the copy / paste menu to be dismissed. Fabric will call all props handlers when a single prop changed, so if the `selection` prop changed the `placeholder` prop handler would be called too. To fix this we can check that the value changed before calling `setHint`.

## Changelog:

[ANDROID] [FIXED] - Fix copy / paste menu and simplify controlled text selection on Android

Pull Request resolved: #37424

Test Plan:
Tested on new and old arch in RNTester example.

Before:

https://github.com/facebook/react-native/assets/2677334/a915b62a-dd79-4adb-9d95-2317780431cf

After:

https://github.com/facebook/react-native/assets/2677334/0dd475ed-8981-410c-8908-f00998dcc425

Reviewed By: cortinico

Differential Revision: D45958425

Pulled By: NickGerleman

fbshipit-source-id: 7b90c1270274f6621303efa60b5398b1a49276ca
  • Loading branch information
janicduplessis authored and facebook-github-bot committed May 24, 2023
1 parent a449291 commit d4f6cf1
Show file tree
Hide file tree
Showing 8 changed files with 24 additions and 146 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,6 @@ export const __INTERNAL_VIEW_CONFIG: PartialViewConfig = {
fontStyle: true,
textShadowOffset: true,
selectionColor: {process: require('../../StyleSheet/processColor').default},
selection: true,
placeholderTextColor: {
process: require('../../StyleSheet/processColor').default,
},
Expand Down
25 changes: 5 additions & 20 deletions packages/react-native/Libraries/Components/TextInput/TextInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -1066,27 +1066,19 @@ function InternalTextInput(props: Props): React.Node {
accessibilityState,
id,
tabIndex,
selection: propsSelection,
...otherProps
} = props;

const inputRef = useRef<null | React.ElementRef<HostComponent<mixed>>>(null);

// Android sends a "onTextChanged" event followed by a "onSelectionChanged" event, for
// the same "most recent event count".
// For controlled selection, that means that immediately after text is updated,
// a controlled component will pass in the *previous* selection, even if the controlled
// component didn't mean to modify the selection at all.
// Therefore, we ignore selections and pass them through until the selection event has
// been sent.
// Note that this mitigation is NOT needed for Fabric.
// discovered when upgrading react-hooks
// eslint-disable-next-line react-hooks/exhaustive-deps
let selection: ?Selection =
props.selection == null
const selection: ?Selection =
propsSelection == null
? null
: {
start: props.selection.start,
end: props.selection.end ?? props.selection.start,
start: propsSelection.start,
end: propsSelection.end ?? propsSelection.start,
};

const [mostRecentEventCount, setMostRecentEventCount] = useState<number>(0);
Expand All @@ -1098,12 +1090,6 @@ function InternalTextInput(props: Props): React.Node {
|}>({selection, mostRecentEventCount});

const lastNativeSelection = lastNativeSelectionState.selection;
const lastNativeSelectionEventCount =
lastNativeSelectionState.mostRecentEventCount;

if (lastNativeSelectionEventCount < mostRecentEventCount) {
selection = null;
}

let viewCommands;
if (AndroidTextInputCommands) {
Expand Down Expand Up @@ -1503,7 +1489,6 @@ function InternalTextInput(props: Props): React.Node {
onScroll={_onScroll}
onSelectionChange={_onSelectionChange}
placeholder={placeholder}
selection={selection}
style={style}
text={text}
textBreakStrategy={props.textBreakStrategy}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ public class ReactTextUpdate {
private final float mPaddingBottom;
private final int mTextAlign;
private final int mTextBreakStrategy;
private final int mSelectionStart;
private final int mSelectionEnd;
private final int mJustificationMode;

/**
Expand All @@ -55,35 +53,7 @@ public ReactTextUpdate(
paddingBottom,
textAlign,
Layout.BREAK_STRATEGY_HIGH_QUALITY,
Layout.JUSTIFICATION_MODE_NONE,
-1,
-1);
}

public ReactTextUpdate(
Spannable text,
int jsEventCounter,
boolean containsImages,
float paddingStart,
float paddingTop,
float paddingEnd,
float paddingBottom,
int textAlign,
int textBreakStrategy,
int justificationMode) {
this(
text,
jsEventCounter,
containsImages,
paddingStart,
paddingTop,
paddingEnd,
paddingBottom,
textAlign,
textBreakStrategy,
justificationMode,
-1,
-1);
Layout.JUSTIFICATION_MODE_NONE);
}

public ReactTextUpdate(
Expand All @@ -103,9 +73,7 @@ public ReactTextUpdate(
UNSET,
textAlign,
textBreakStrategy,
justificationMode,
-1,
-1);
justificationMode);
}

public ReactTextUpdate(
Expand All @@ -118,9 +86,7 @@ public ReactTextUpdate(
float paddingBottom,
int textAlign,
int textBreakStrategy,
int justificationMode,
int selectionStart,
int selectionEnd) {
int justificationMode) {
mText = text;
mJsEventCounter = jsEventCounter;
mContainsImages = containsImages;
Expand All @@ -130,8 +96,6 @@ public ReactTextUpdate(
mPaddingBottom = paddingBottom;
mTextAlign = textAlign;
mTextBreakStrategy = textBreakStrategy;
mSelectionStart = selectionStart;
mSelectionEnd = selectionEnd;
mJustificationMode = justificationMode;
}

Expand Down Expand Up @@ -187,12 +151,4 @@ public int getTextBreakStrategy() {
public int getJustificationMode() {
return mJustificationMode;
}

public int getSelectionStart() {
return mSelectionStart;
}

public int getSelectionEnd() {
return mSelectionEnd;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ public class ReactEditText extends AppCompatEditText
private int mFontStyle = UNSET;
private boolean mAutoFocus = false;
private boolean mDidAttachToWindow = false;
private @Nullable String mPlaceholder = null;

private ReactViewBackgroundManager mReactBackgroundManager;

Expand Down Expand Up @@ -497,6 +498,13 @@ public void setInputType(int type) {
setKeyListener(mKeyListener);
}

public void setPlaceholder(@Nullable String placeholder) {
if (!Objects.equals(placeholder, mPlaceholder)) {
mPlaceholder = placeholder;
setHint(placeholder);
}
}

public void setFontFamily(String fontFamily) {
mFontFamily = fontFamily;
mTypefaceDirty = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -328,21 +328,19 @@ public void receiveCommand(

if (!args.isNull(1)) {
String text = args.getString(1);
reactEditText.maybeSetTextFromJS(
getReactTextUpdate(text, mostRecentEventCount, start, end));
reactEditText.maybeSetTextFromJS(getReactTextUpdate(text, mostRecentEventCount));
}
reactEditText.maybeSetSelection(mostRecentEventCount, start, end);
break;
}
}

private ReactTextUpdate getReactTextUpdate(
String text, int mostRecentEventCount, int start, int end) {
private ReactTextUpdate getReactTextUpdate(String text, int mostRecentEventCount) {
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append(TextTransform.apply(text, TextTransform.UNSET));

return new ReactTextUpdate(
sb, mostRecentEventCount, false, 0, 0, 0, 0, Gravity.NO_GRAVITY, 0, 0, start, end);
sb, mostRecentEventCount, false, 0, 0, 0, 0, Gravity.NO_GRAVITY, 0, 0);
}

@Override
Expand Down Expand Up @@ -373,9 +371,9 @@ public void updateExtraData(ReactEditText view, Object extraData) {

// Ensure that selection is handled correctly on text update
boolean isCurrentSelectionEmpty = view.getSelectionStart() == view.getSelectionEnd();
int selectionStart = update.getSelectionStart();
int selectionEnd = update.getSelectionEnd();
if ((selectionStart == UNSET || selectionEnd == UNSET) && isCurrentSelectionEmpty) {
int selectionStart = UNSET;
int selectionEnd = UNSET;
if (isCurrentSelectionEmpty) {
// if selection is not set by state, shift current selection to ensure constant gap to
// text end
int textLength = view.getText() == null ? 0 : view.getText().length();
Expand Down Expand Up @@ -507,7 +505,7 @@ public void setAllowFontScaling(ReactEditText view, boolean allowFontScaling) {

@ReactProp(name = "placeholder")
public void setPlaceholder(ReactEditText view, String placeholder) {
view.setHint(placeholder);
view.setPlaceholder(placeholder);
}

@ReactProp(name = "placeholderTextColor", customType = "Color")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.R;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.uimanager.Spacing;
Expand All @@ -46,13 +45,10 @@ public class ReactTextInputShadowNode extends ReactBaseTextShadowNode

@VisibleForTesting public static final String PROP_TEXT = "text";
@VisibleForTesting public static final String PROP_PLACEHOLDER = "placeholder";
@VisibleForTesting public static final String PROP_SELECTION = "selection";

// Represents the {@code text} property only, not possible nested content.
private @Nullable String mText = null;
private @Nullable String mPlaceholder = null;
private int mSelectionStart = UNSET;
private int mSelectionEnd = UNSET;

public ReactTextInputShadowNode(
@Nullable ReactTextViewManagerCallback reactTextViewManagerCallback) {
Expand Down Expand Up @@ -167,18 +163,6 @@ public void setMostRecentEventCount(int mostRecentEventCount) {
@ReactProp(name = PROP_TEXT)
public void setText(@Nullable String text) {
mText = text;
if (text != null) {
// The selection shouldn't be bigger than the length of the text
if (mSelectionStart > text.length()) {
mSelectionStart = text.length();
}
if (mSelectionEnd > text.length()) {
mSelectionEnd = text.length();
}
} else {
mSelectionStart = UNSET;
mSelectionEnd = UNSET;
}
markUpdated();
}

Expand All @@ -196,18 +180,6 @@ public void setPlaceholder(@Nullable String placeholder) {
return mPlaceholder;
}

@ReactProp(name = PROP_SELECTION)
public void setSelection(@Nullable ReadableMap selection) {
mSelectionStart = mSelectionEnd = UNSET;
if (selection == null) return;

if (selection.hasKey("start") && selection.hasKey("end")) {
mSelectionStart = selection.getInt("start");
mSelectionEnd = selection.getInt("end");
markUpdated();
}
}

@Override
public void setTextBreakStrategy(@Nullable String textBreakStrategy) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Expand Down Expand Up @@ -247,9 +219,7 @@ public void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) {
getPadding(Spacing.BOTTOM),
mTextAlign,
mTextBreakStrategy,
mJustificationMode,
mSelectionStart,
mSelectionEnd);
mJustificationMode);
uiViewOperationQueue.enqueueUpdateExtraData(getReactTag(), reactTextUpdate);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,6 @@ AndroidTextInputProps::AndroidTextInputProps(
"selectionColor",
sourceProps.selectionColor,
{})),
selection(CoreFeatures::enablePropIteratorSetter? sourceProps.selection :
convertRawProp(context, rawProps, "selection", sourceProps.selection, {})),
value(CoreFeatures::enablePropIteratorSetter? sourceProps.value : convertRawProp(context, rawProps, "value", sourceProps.value, {})),
defaultValue(CoreFeatures::enablePropIteratorSetter? sourceProps.defaultValue : convertRawProp(context, rawProps,
"defaultValue",
Expand Down Expand Up @@ -349,7 +347,6 @@ void AndroidTextInputProps::setProp(
RAW_SET_PROP_SWITCH_CASE_BASIC(placeholderTextColor);
RAW_SET_PROP_SWITCH_CASE_BASIC(secureTextEntry);
RAW_SET_PROP_SWITCH_CASE_BASIC(selectionColor);
RAW_SET_PROP_SWITCH_CASE_BASIC(selection);
RAW_SET_PROP_SWITCH_CASE_BASIC(defaultValue);
RAW_SET_PROP_SWITCH_CASE_BASIC(selectTextOnFocus);
RAW_SET_PROP_SWITCH_CASE_BASIC(submitBehavior);
Expand Down Expand Up @@ -449,7 +446,6 @@ folly::dynamic AndroidTextInputProps::getDynamic() const {
props["placeholderTextColor"] = toAndroidRepr(placeholderTextColor);
props["secureTextEntry"] = secureTextEntry;
props["selectionColor"] = toAndroidRepr(selectionColor);
props["selection"] = toDynamic(selection);
props["value"] = value;
props["defaultValue"] = defaultValue;
props["selectTextOnFocus"] = selectTextOnFocus;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,32 +26,6 @@

namespace facebook::react {

struct AndroidTextInputSelectionStruct {
int start;
int end;
};

static inline void fromRawValue(
const PropsParserContext &context,
const RawValue &value,
AndroidTextInputSelectionStruct &result) {
auto map = (butter::map<std::string, RawValue>)value;

auto start = map.find("start");
if (start != map.end()) {
fromRawValue(context, start->second, result.start);
}
auto end = map.find("end");
if (end != map.end()) {
fromRawValue(context, end->second, result.end);
}
}

static inline std::string toString(
const AndroidTextInputSelectionStruct &value) {
return "[Object AndroidTextInputSelectionStruct]";
}

struct AndroidTextInputTextShadowOffsetStruct {
double width;
double height;
Expand Down Expand Up @@ -86,13 +60,6 @@ inline folly::dynamic toDynamic(
dynamicValue["height"] = value.height;
return dynamicValue;
}

inline folly::dynamic toDynamic(const AndroidTextInputSelectionStruct &value) {
folly::dynamic dynamicValue = folly::dynamic::object();
dynamicValue["start"] = value.start;
dynamicValue["end"] = value.end;
return dynamicValue;
}
#endif

class AndroidTextInputProps final : public ViewProps, public BaseTextProps {
Expand Down Expand Up @@ -137,7 +104,6 @@ class AndroidTextInputProps final : public ViewProps, public BaseTextProps {
SharedColor placeholderTextColor{};
bool secureTextEntry{false};
SharedColor selectionColor{};
AndroidTextInputSelectionStruct selection{};
std::string value{};
std::string defaultValue{};
bool selectTextOnFocus{false};
Expand Down

0 comments on commit d4f6cf1

Please sign in to comment.