mirror of
https://github.com/facebook/react-native.git
synced 2025-11-01 09:14:26 +00:00
694e22de84
Summary: I noticed when porting my iOS app to macOS via Catalyst that the text rendering was somewhat different on the two platforms. Text looked blurry and over-weight on macOS, even when disabling the Catalyst scaling transform. I hazily remembered that I'd seen this problem before in my old Cocoa development days: this kind of blurring occurs when rendering text with sub-pixel anti-aliasing into an offscreen buffer which will then be traditionally composited, because when the SPAA algorithm attempts to blend with the underlying content (i.e. in the offscreen buffer), there isn't any. SPAA is disabled on iOS, so the issue wouldn't appear there. On macOS, typical approachs to displaying text (e.g. `CATextLayer`) normally disable SPAA, since it's been incompatible with the platform's compositing strategy since the transition to layer-backed views some years ago. But React Native uses `NSLayoutManager` to rasterize text (rather than relying on the system render server via `CATextLayer`), and that class doesn't touch the context's font smoothing bit before drawing. This change makes macOS/Catalyst text rendering consistent with iOS text rendering by disabling SPAA. It appears that the code I've modified is in the process of being refactored (for Fabric?). It looks like [this](https://github.com/facebook/react-native/blob/8d6b41e9bcede07fb627d57cf6c11050ae590d57/ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTTextLayoutManager.mm#L111) is the corresponding place in the new code (sammy-SC, is that right?). I'm happy to include a change to the new renderer in this patch if someone can point me at how to test that change. ## Changelog [iOS] [Fixed] - Improved text rendering on macOS Catalyst Pull Request resolved: https://github.com/facebook/react-native/pull/29609 Test Plan: 1. Prepare RNTester for running on macOS (or apply [this patch](https://gist.github.com/andymatuschak/d0f5b4fc1a28efc4f860801aa1deddcd) to handle parts 1 and 2, but you'll still need to do part 3): 1. Open the workspace, navigate to the `RNTester` target's configuration, and check the "Mac" checkbox under "Deployment Info. 2. Flipper doesn't yet compile for Catalyst (https://github.com/facebook/react-native/issues/27845), so you must disable it by: a) commenting out `use_flipper!` and `flipper_post_install` in the Podfile, then running `pod install`; and b) removing the `FB_SONARKIT_ENABLED` preprocessor flags in the Xcode project. 3. macOS has different signing rules from iOS; you must set a development team in the "Signing & Capabilities" tab of the `RNTester` target configuration pane. Unfortunately, you must also do this in the `Pods` project for the `React-Core-AccessibilityResources` target ([this is an issue which CocoaPods must fix](https://github.com/CocoaPods/CocoaPods/issues/8891)). 2. Run RNTester with and without the patch. You'll see that the font hinting is overweight without the patch; see screenshots below (incorrect rendering above, correct rendering below; note that fonts still remain slightly blurred because of Catalyst's window scaling transform, but that's removed on Big Sur).   Reviewed By: PeteTheHeat Differential Revision: D23344751 Pulled By: sammy-SC fbshipit-source-id: 1bbf682b681e381a8a90e152245d9b0df8ec7697
283 lines
7.9 KiB
Objective-C
283 lines
7.9 KiB
Objective-C
/*
|
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
*
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
*/
|
|
|
|
#import <React/RCTTextView.h>
|
|
|
|
#import <MobileCoreServices/UTCoreTypes.h>
|
|
|
|
#import <React/RCTUtils.h>
|
|
#import <React/UIView+React.h>
|
|
|
|
#import <React/RCTTextShadowView.h>
|
|
|
|
@implementation RCTTextView
|
|
{
|
|
CAShapeLayer *_highlightLayer;
|
|
UILongPressGestureRecognizer *_longPressGestureRecognizer;
|
|
|
|
NSArray<UIView *> *_Nullable _descendantViews;
|
|
NSTextStorage *_Nullable _textStorage;
|
|
CGRect _contentFrame;
|
|
}
|
|
|
|
- (instancetype)initWithFrame:(CGRect)frame
|
|
{
|
|
if (self = [super initWithFrame:frame]) {
|
|
self.isAccessibilityElement = YES;
|
|
self.accessibilityTraits |= UIAccessibilityTraitStaticText;
|
|
self.opaque = NO;
|
|
self.contentMode = UIViewContentModeRedraw;
|
|
}
|
|
return self;
|
|
}
|
|
|
|
- (NSString *)description
|
|
{
|
|
NSString *superDescription = super.description;
|
|
NSRange semicolonRange = [superDescription rangeOfString:@";"];
|
|
NSString *replacement = [NSString stringWithFormat:@"; reactTag: %@; text: %@", self.reactTag, _textStorage.string];
|
|
return [superDescription stringByReplacingCharactersInRange:semicolonRange withString:replacement];
|
|
}
|
|
|
|
- (void)setSelectable:(BOOL)selectable
|
|
{
|
|
if (_selectable == selectable) {
|
|
return;
|
|
}
|
|
|
|
_selectable = selectable;
|
|
|
|
if (_selectable) {
|
|
[self enableContextMenu];
|
|
}
|
|
else {
|
|
[self disableContextMenu];
|
|
}
|
|
}
|
|
|
|
- (void)reactSetFrame:(CGRect)frame
|
|
{
|
|
// Text looks super weird if its frame is animated.
|
|
// This disables the frame animation, without affecting opacity, etc.
|
|
[UIView performWithoutAnimation:^{
|
|
[super reactSetFrame:frame];
|
|
}];
|
|
}
|
|
|
|
- (void)didUpdateReactSubviews
|
|
{
|
|
// Do nothing, as subviews are managed by `setTextStorage:` method
|
|
}
|
|
|
|
- (void)setTextStorage:(NSTextStorage *)textStorage
|
|
contentFrame:(CGRect)contentFrame
|
|
descendantViews:(NSArray<UIView *> *)descendantViews
|
|
{
|
|
_textStorage = textStorage;
|
|
_contentFrame = contentFrame;
|
|
|
|
// FIXME: Optimize this.
|
|
for (UIView *view in _descendantViews) {
|
|
[view removeFromSuperview];
|
|
}
|
|
|
|
_descendantViews = descendantViews;
|
|
|
|
for (UIView *view in descendantViews) {
|
|
[self addSubview:view];
|
|
}
|
|
|
|
[self setNeedsDisplay];
|
|
}
|
|
|
|
- (void)drawRect:(CGRect)rect
|
|
{
|
|
[super drawRect:rect];
|
|
if (!_textStorage) {
|
|
return;
|
|
}
|
|
|
|
|
|
NSLayoutManager *layoutManager = _textStorage.layoutManagers.firstObject;
|
|
NSTextContainer *textContainer = layoutManager.textContainers.firstObject;
|
|
|
|
#if TARGET_OS_MACCATALYST
|
|
CGContextRef context = UIGraphicsGetCurrentContext();
|
|
CGContextSaveGState(context);
|
|
// NSLayoutManager tries to draw text with sub-pixel anti-aliasing by default on
|
|
// macOS, but rendering SPAA onto a transparent background produces poor results.
|
|
// CATextLayer disables font smoothing by default now on macOS; we follow suit.
|
|
CGContextSetShouldSmoothFonts(context, NO);
|
|
#endif
|
|
|
|
NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer];
|
|
[layoutManager drawBackgroundForGlyphRange:glyphRange atPoint:_contentFrame.origin];
|
|
[layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:_contentFrame.origin];
|
|
|
|
__block UIBezierPath *highlightPath = nil;
|
|
NSRange characterRange = [layoutManager characterRangeForGlyphRange:glyphRange
|
|
actualGlyphRange:NULL];
|
|
[_textStorage enumerateAttribute:RCTTextAttributesIsHighlightedAttributeName
|
|
inRange:characterRange
|
|
options:0
|
|
usingBlock:
|
|
^(NSNumber *value, NSRange range, __unused BOOL *stop) {
|
|
if (!value.boolValue) {
|
|
return;
|
|
}
|
|
|
|
[layoutManager enumerateEnclosingRectsForGlyphRange:range
|
|
withinSelectedGlyphRange:range
|
|
inTextContainer:textContainer
|
|
usingBlock:
|
|
^(CGRect enclosingRect, __unused BOOL *anotherStop) {
|
|
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(enclosingRect, -2, -2) cornerRadius:2];
|
|
if (highlightPath) {
|
|
[highlightPath appendPath:path];
|
|
} else {
|
|
highlightPath = path;
|
|
}
|
|
}
|
|
];
|
|
}];
|
|
|
|
if (highlightPath) {
|
|
if (!_highlightLayer) {
|
|
_highlightLayer = [CAShapeLayer layer];
|
|
_highlightLayer.fillColor = [UIColor colorWithWhite:0 alpha:0.25].CGColor;
|
|
[self.layer addSublayer:_highlightLayer];
|
|
}
|
|
_highlightLayer.position = _contentFrame.origin;
|
|
_highlightLayer.path = highlightPath.CGPath;
|
|
} else {
|
|
[_highlightLayer removeFromSuperlayer];
|
|
_highlightLayer = nil;
|
|
}
|
|
|
|
#if TARGET_OS_MACCATALYST
|
|
CGContextRestoreGState(context);
|
|
#endif
|
|
}
|
|
|
|
|
|
- (NSNumber *)reactTagAtPoint:(CGPoint)point
|
|
{
|
|
NSNumber *reactTag = self.reactTag;
|
|
|
|
CGFloat fraction;
|
|
NSLayoutManager *layoutManager = _textStorage.layoutManagers.firstObject;
|
|
NSTextContainer *textContainer = layoutManager.textContainers.firstObject;
|
|
NSUInteger characterIndex = [layoutManager characterIndexForPoint:point
|
|
inTextContainer:textContainer
|
|
fractionOfDistanceBetweenInsertionPoints:&fraction];
|
|
|
|
// If the point is not before (fraction == 0.0) the first character and not
|
|
// after (fraction == 1.0) the last character, then the attribute is valid.
|
|
if (_textStorage.length > 0 && (fraction > 0 || characterIndex > 0) && (fraction < 1 || characterIndex < _textStorage.length - 1)) {
|
|
reactTag = [_textStorage attribute:RCTTextAttributesTagAttributeName atIndex:characterIndex effectiveRange:NULL];
|
|
}
|
|
|
|
return reactTag;
|
|
}
|
|
|
|
- (void)didMoveToWindow
|
|
{
|
|
[super didMoveToWindow];
|
|
|
|
if (!self.window) {
|
|
self.layer.contents = nil;
|
|
if (_highlightLayer) {
|
|
[_highlightLayer removeFromSuperlayer];
|
|
_highlightLayer = nil;
|
|
}
|
|
} else if (_textStorage) {
|
|
[self setNeedsDisplay];
|
|
}
|
|
}
|
|
|
|
#pragma mark - Accessibility
|
|
|
|
- (NSString *)accessibilityLabel
|
|
{
|
|
NSString *superAccessibilityLabel = [super accessibilityLabel];
|
|
if (superAccessibilityLabel) {
|
|
return superAccessibilityLabel;
|
|
}
|
|
return _textStorage.string;
|
|
}
|
|
|
|
#pragma mark - Context Menu
|
|
|
|
- (void)enableContextMenu
|
|
{
|
|
_longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
|
|
[self addGestureRecognizer:_longPressGestureRecognizer];
|
|
}
|
|
|
|
- (void)disableContextMenu
|
|
{
|
|
[self removeGestureRecognizer:_longPressGestureRecognizer];
|
|
_longPressGestureRecognizer = nil;
|
|
}
|
|
|
|
- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture
|
|
{
|
|
// TODO: Adopt showMenuFromRect (necessary for UIKitForMac)
|
|
#if !TARGET_OS_TV && !TARGET_OS_UIKITFORMAC
|
|
UIMenuController *menuController = [UIMenuController sharedMenuController];
|
|
|
|
if (menuController.isMenuVisible) {
|
|
return;
|
|
}
|
|
|
|
if (!self.isFirstResponder) {
|
|
[self becomeFirstResponder];
|
|
}
|
|
|
|
[menuController setTargetRect:self.bounds inView:self];
|
|
[menuController setMenuVisible:YES animated:YES];
|
|
#endif
|
|
}
|
|
|
|
- (BOOL)canBecomeFirstResponder
|
|
{
|
|
return _selectable;
|
|
}
|
|
|
|
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
|
|
{
|
|
if (_selectable && action == @selector(copy:)) {
|
|
return YES;
|
|
}
|
|
|
|
return [self.nextResponder canPerformAction:action withSender:sender];
|
|
}
|
|
|
|
- (void)copy:(id)sender
|
|
{
|
|
#if !TARGET_OS_TV
|
|
NSAttributedString *attributedText = _textStorage;
|
|
|
|
NSMutableDictionary *item = [NSMutableDictionary new];
|
|
|
|
NSData *rtf = [attributedText dataFromRange:NSMakeRange(0, attributedText.length)
|
|
documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFDTextDocumentType}
|
|
error:nil];
|
|
|
|
if (rtf) {
|
|
[item setObject:rtf forKey:(id)kUTTypeFlatRTFD];
|
|
}
|
|
|
|
[item setObject:attributedText.string forKey:(id)kUTTypeUTF8PlainText];
|
|
|
|
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
|
|
pasteboard.items = @[item];
|
|
#endif
|
|
}
|
|
|
|
@end
|