Skip to content

Support arbitrary selectable text in Text component #1346

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 26 commits into from
Oct 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
e23bf89
Support arbitrary selectable text in Text component
lyahdav Mar 31, 2021
c8917ad
Fix GH tags
Aug 10, 2022
13ac427
Revert RNTesterPage style change
Aug 10, 2022
a4d3720
Merge remote-tracking branch 'microsoft/main' into text-selection
Aug 10, 2022
46606cd
Fix hit-testing in RCTTextView for selection
appden Jun 29, 2021
a4d20e0
Merge remote-tracking branch 'microsoft/main' into text-selection
Aug 17, 2022
007317f
Merge remote-tracking branch 'microsoft/main' into text-selection
Aug 29, 2022
4a64054
Merge branch 'main' into text-selection
shwanton Sep 8, 2022
7d3b7ee
Merge remote-tracking branch 'microsoft/main' into text-selection
Sep 9, 2022
c3231cf
Merge remote-tracking branch 'microsoft/main' into text-selection
Sep 12, 2022
0b7743a
Revert changes to touch handler
Sep 14, 2022
655c33a
Only keep NSTextView changes
Sep 14, 2022
df41b3b
Merge branch 'main' of github.com:microsoft/react-native-macos into t…
Sep 15, 2022
bc083f9
Merge branch 'text-selection' of github.com:shwanton/react-native-mac…
Sep 15, 2022
2364192
Remove unused property
Sep 15, 2022
b08aae9
Re-add focus ring for selected text
Sep 15, 2022
b72d4bc
Fix typos
Sep 15, 2022
eafbb5f
Ensure that RCTTextView manages the key loop view
Sep 23, 2022
b13a21f
Merge remote-tracking branch 'microsoft/main' into text-selection
Sep 28, 2022
948b162
move focusable property lower in list
Sep 28, 2022
96421cb
Fix macos tags
Sep 28, 2022
a9b9d13
Merge remote-tracking branch 'microsoft/main' into text-selection
Oct 5, 2022
e8c32de
Remove iOS only highlighted prop that was causing re-render issues on…
Oct 5, 2022
42af687
Merge remote-tracking branch 'microsoft/main' into text-selection
Oct 11, 2022
feb63ab
Merge remote-tracking branch 'microsoft/main' into text-selection
Oct 18, 2022
9f49a9c
yarn lint
Oct 18, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Libraries/Components/View/ReactNativeViewAttributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const UIView = {
// [TODO(macOS GH#774)
acceptsFirstMouse: true,
enableFocusRing: true,
focusable: true,
onMouseEnter: true,
onMouseLeave: true,
onDragEnter: true,
Expand Down
8 changes: 0 additions & 8 deletions Libraries/Text/Text.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,9 @@ const Text: React.AbstractComponent<
onResponderTerminationRequest,
onStartShouldSetResponder,
pressRetentionOffset,
suppressHighlighting,
...restProps
} = props;

const [isHighlighted, setHighlighted] = useState(false);

const isPressable =
(onPress != null ||
onLongPress != null ||
Expand All @@ -64,11 +61,9 @@ const Text: React.AbstractComponent<
onLongPress,
onPress,
onPressIn(event) {
setHighlighted(!suppressHighlighting);
onPressIn?.(event);
},
onPressOut(event) {
setHighlighted(false);
onPressOut?.(event);
},
onResponderTerminationRequest_DEPRECATED:
Expand All @@ -86,7 +81,6 @@ const Text: React.AbstractComponent<
onPressOut,
onResponderTerminationRequest,
onStartShouldSetResponder,
suppressHighlighting,
],
);

Expand Down Expand Up @@ -162,7 +156,6 @@ const Text: React.AbstractComponent<
<NativeVirtualText
{...restProps}
{...eventHandlersForText}
isHighlighted={isHighlighted}
isPressable={isPressable}
numberOfLines={numberOfLines}
selectionColor={selectionColor}
Expand All @@ -177,7 +170,6 @@ const Text: React.AbstractComponent<
accessible={accessible !== false}
allowFontScaling={allowFontScaling !== false}
ellipsizeMode={ellipsizeMode ?? 'tail'}
isHighlighted={isHighlighted}
numberOfLines={numberOfLines}
selectionColor={selectionColor}
style={style}
Expand Down
165 changes: 118 additions & 47 deletions Libraries/Text/Text/RCTTextView.m
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,35 @@

#import <QuartzCore/QuartzCore.h> // TODO(macOS GH#774)

#if TARGET_OS_OSX // [TODO(macOS GH#774)

// We are managing the key view loop using the RCTTextView.
// Disable key view for backed NSTextView so we don't get double focus.
@interface RCTUnfocusableTextView : NSTextView
@end

@implementation RCTUnfocusableTextView

- (BOOL)canBecomeKeyView
{
return NO;
}

@end

@interface RCTTextView () <NSTextViewDelegate>
@end

#endif // ]TODO(macOS GH#774)

@implementation RCTTextView
{
CAShapeLayer *_highlightLayer;
#if !TARGET_OS_OSX // TODO(macOS GH#774)
UILongPressGestureRecognizer *_longPressGestureRecognizer;
#else // [TODO(macOS GH#774)
NSString * _accessibilityLabel;
NSTextView *_textView;
#endif // ]TODO(macOS GH#774)

RCTEventDispatcher *_eventDispatcher; // TODO(OSS Candidate ISS#2710739)
Expand Down Expand Up @@ -57,6 +79,18 @@ - (instancetype)initWithFrame:(CGRect)frame
self.accessibilityRole = NSAccessibilityStaticTextRole;
// Fix blurry text on non-retina displays.
self.canDrawSubviewsIntoLayer = YES;
// The NSTextView is responsible for drawing text and managing selection.
_textView = [[RCTUnfocusableTextView alloc] initWithFrame:self.bounds];
_textView.delegate = self;
_textView.usesFontPanel = NO;
_textView.drawsBackground = NO;
_textView.linkTextAttributes = @{};
_textView.editable = NO;
_textView.selectable = NO;
_textView.verticallyResizable = NO;
_textView.layoutManager.usesFontLeading = NO;
_textStorage = _textView.textStorage;
[self addSubview:_textView];
#endif // ]TODO(macOS GH#774)
self.opaque = NO;
RCTUIViewSetContentModeRedraw(self); // TODO(macOS GH#774) and TODO(macOS ISS#3536887)
Expand All @@ -65,40 +99,7 @@ - (instancetype)initWithFrame:(CGRect)frame
}

#if TARGET_OS_OSX // [TODO(macOS GH#774)
- (void)dealloc
{
[self removeAllTextStorageLayoutManagers];
}

- (void)removeAllTextStorageLayoutManagers
{
// On macOS AppKit can throw an uncaught exception
// (-[NSConcretePointerArray pointerAtIndex:]: attempt to access pointer at index ...)
// during the dealloc of NSLayoutManager. The _textStorage and its
// associated NSLayoutManager dealloc later in an autorelease pool.
// Manually removing the layout managers from _textStorage prior to release
// works around this issue in AppKit.
NSArray<NSLayoutManager *> *managers = [[_textStorage layoutManagers] copy];
for (NSLayoutManager *manager in managers) {
[_textStorage removeLayoutManager:manager];
}
}

- (BOOL)canBecomeKeyView
{
// RCTText should not get any keyboard focus unless its `selectable` prop is true
return _selectable;
}

- (void)drawFocusRingMask {
if ([self enableFocusRing]) {
NSRectFill([self bounds]);
}
}

- (NSRect)focusRingMaskBounds {
return [self bounds];
}
#endif // ]TODO(macOS GH#774)

#if DEBUG // TODO(macOS GH#774) description is a debug-only feature
Expand All @@ -119,14 +120,19 @@ - (void)setSelectable:(BOOL)selectable

_selectable = selectable;

#if !TARGET_OS_OSX // TODO(macOS GH#774)
#if !TARGET_OS_OSX // [TODO(macOS GH#774)
if (_selectable) {
[self enableContextMenu];
}
else {
[self disableContextMenu];
}
#endif // TODO(macOS GH#774)
#else
_textView.selectable = _selectable;
if (_selectable) {
[self setFocusable:YES];
}
#endif // ]TODO(macOS GH#774)
}

#if !TARGET_OS_OSX // TODO(macOS GH#774)
Expand All @@ -149,13 +155,37 @@ - (void)setTextStorage:(NSTextStorage *)textStorage
contentFrame:(CGRect)contentFrame
descendantViews:(NSArray<RCTUIView *> *)descendantViews // TODO(macOS ISS#3536887)
{
#if TARGET_OS_OSX // [TODO(macOS GH#774)
[self removeAllTextStorageLayoutManagers];
// This lets the textView own its text storage on macOS
// We update and replace the text container `_textView.textStorage.attributedString` when text/layout changes
#if !TARGET_OS_OSX // [TODO(macOS GH#774)
_textStorage = textStorage;
#endif // ]TODO(macOS GH#774)

_textStorage = textStorage;
_contentFrame = contentFrame;

#if TARGET_OS_OSX // [TODO(macOS GH#774)
NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject;
NSTextContainer *textContainer = layoutManager.textContainers.firstObject;

[_textView replaceTextContainer:textContainer];

// On macOS AppKit can throw an uncaught exception
// (-[NSConcretePointerArray pointerAtIndex:]: attempt to access pointer at index ...)
// during the dealloc of NSLayoutManager. The textStorage and its
// associated NSLayoutManager dealloc later in an autorelease pool.
// Manually removing the layout managers from textStorage prior to release
// works around this issue in AppKit.
NSArray<NSLayoutManager *> *managers = [[textStorage layoutManagers] copy];
for (NSLayoutManager *manager in managers) {
[textStorage removeLayoutManager:manager];
}

_textView.minSize = contentFrame.size;
_textView.maxSize = contentFrame.size;
_textView.frame = contentFrame;
_textView.textStorage.attributedString = textStorage;
#endif // ]TODO(macOS GH#774)

// FIXME: Optimize this.
for (RCTUIView *view in _descendantViews) { // TODO(macOS ISS#3536887)
[view removeFromSuperview];
Expand All @@ -173,6 +203,13 @@ - (void)setTextStorage:(NSTextStorage *)textStorage
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];

// For iOS, UITextView api is not used for legacy performance reasons. A custom draw implementation is used instead.
// On desktop, we use NSTextView to access api's for arbitrary selection, custom cursors etc...
#if TARGET_OS_OSX // [TODO(macOS GH#774)
return;
#endif // ]TODO(macOS GH#774)

if (!_textStorage) {
return;
}
Expand Down Expand Up @@ -408,6 +445,39 @@ - (void)rightMouseDown:(NSEvent *)event
}
}
}
#endif // ]TODO(macOS GH#774)

#pragma mark - Selection

#if TARGET_OS_OSX // [TODO(macOS GH#774)
- (void)textDidEndEditing:(NSNotification *)notification
{
_textView.selectedRange = NSMakeRange(NSNotFound, 0);
}
#endif // ]TODO(macOS GH#774)

#pragma mark - Responder chain

#if !TARGET_OS_OSX // TODO(macOS GH#774)
- (BOOL)canBecomeFirstResponder
{
return _selectable;
}
#else
- (BOOL)canBecomeKeyView
{
return self.focusable;
}

- (void)drawFocusRingMask {
if (self.focusable && self.enableFocusRing) {
NSRectFill([self bounds]);
}
}

- (NSRect)focusRingMaskBounds {
return [self bounds];
}

- (BOOL)becomeFirstResponder
{
Expand All @@ -423,22 +493,19 @@ - (BOOL)becomeFirstResponder

- (BOOL)resignFirstResponder
{
if (![super resignFirstResponder]) {
// Don't relinquish first responder while selecting text.
if (_selectable && NSRunLoop.currentRunLoop.currentMode == NSEventTrackingRunLoopMode) {
return NO;
}

// If we've lost focus, notify listeners
[_eventDispatcher sendEvent:[RCTFocusChangeEvent blurEventWithReactTag:self.reactTag]];

return YES;

return [super resignFirstResponder];
}

#endif // ]TODO(macOS GH#774)

- (BOOL)canBecomeFirstResponder
{
return _selectable;
return self.focusable;
}
#endif

#if !TARGET_OS_OSX // TODO(macOS GH#774)
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
Expand All @@ -451,6 +518,8 @@ - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
}
#endif // TODO(macOS GH#774)

#pragma mark - Copy/Paste

- (void)copy:(id)sender
{
NSAttributedString *attributedText = _textStorage;
Expand All @@ -470,6 +539,8 @@ - (void)copy:(id)sender
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.items = @[item];
#elif TARGET_OS_OSX // TODO(macOS GH#774)
[_textView copy:sender];

NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
[pasteboard writeObjects:[NSArray arrayWithObjects:attributedText.string, rtf, nil]];
Expand Down
1 change: 1 addition & 0 deletions Libraries/Text/TextNativeComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export const NativeText: HostComponent<NativeTextProps> =
isPressable: true,
numberOfLines: true,
ellipsizeMode: true,
focusable: true,
allowFontScaling: true,
dynamicTypeRamp: true,
maxFontSizeMultiplier: true,
Expand Down
12 changes: 12 additions & 0 deletions Libraries/Text/TextProps.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,4 +225,16 @@ export type TextProps = $ReadOnly<{|
* Specifies the Tooltip for the button view
*/
tooltip?: ?string,

/**
* When `true`, indicates that the text can be focused in key view loop
* By default, when `selectable={true}` the text view will be focusable unless disabled
*/
focusable?: ?boolean,

/**
* Specifies whether focus ring should be drawn when the view has the first responder status.
* Only works when `focusable={true}`
*/
enableFocusRing?: ?boolean, // TODO(macOS GH#774)
|}>;
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ function KeyEventExample(): React.Node {
validKeysDown={['g', 'Escape', 'Enter', 'ArrowLeft']}
onKeyDown={e => appendLog('Key Down:' + e.nativeEvent.key)}
validKeysUp={['c', 'd']}
onKeyUp={e => appendLog('Key Up:' + e.nativeEvent.key)}></View>
onKeyUp={e => appendLog('Key Up:' + e.nativeEvent.key)}
/>
<Text style={styles.title}>TextInput</Text>
<Text style={styles.text}>
validKeysDown: [ArrowRight, ArrowDown]{'\n'}
Expand Down
Loading