Open History to see the last commit
1#import "T3MarkdownText.h"
2#import "T3MarkdownTextShadowNode.h"
3#import "T3MarkdownTextComponentDescriptor.h"
4#import "T3MarkdownTextRun.h"
5#import <React/RCTConversions.h>
6#import <objc/runtime.h>
7
8#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
9#import <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
10#import <react/renderer/components/T3MarkdownTextSpec/Props.h>
11#import <react/renderer/components/T3MarkdownTextSpec/RCTComponentViewHelpers.h>
12#import "RCTFabricComponentsPlugins.h"
13
14using namespace facebook::react;
15
16static void T3MarkdownTextApplyParagraphStyles(
17 NSMutableAttributedString *attributedString,
18 const std::vector<T3MarkdownTextParagraphStyleRange> &styleRanges)
19{
20 for (const auto &styleRange : styleRanges) {
21 if (styleRange.length == 0 || styleRange.location >= attributedString.length) {
22 continue;
23 }
24
25 const NSRange markerRange = NSMakeRange(
26 styleRange.location,
27 MIN(styleRange.length, attributedString.length - styleRange.location));
28 const NSRange paragraphRange = [attributedString.string paragraphRangeForRange:markerRange];
29 const NSParagraphStyle *existingStyle =
30 [attributedString attribute:NSParagraphStyleAttributeName
31 atIndex:paragraphRange.location
32 effectiveRange:nil];
33 NSMutableParagraphStyle *paragraphStyle =
34 existingStyle ? [existingStyle mutableCopy] : [NSMutableParagraphStyle new];
35 paragraphStyle.firstLineHeadIndent = styleRange.firstLineHeadIndent;
36 paragraphStyle.headIndent = styleRange.headIndent;
37 paragraphStyle.paragraphSpacing = styleRange.paragraphSpacing;
38 paragraphStyle.tabStops = @[
39 [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft
40 location:styleRange.headIndent
41 options:@{}]
42 ];
43 paragraphStyle.defaultTabInterval = styleRange.headIndent;
44 [attributedString addAttribute:NSParagraphStyleAttributeName
45 value:paragraphStyle
46 range:paragraphRange];
47 }
48}
49
50static void T3MarkdownTextApplyAttachments(
51 NSMutableAttributedString *attributedString,
52 const std::vector<T3MarkdownTextAttachmentRange> &attachmentRanges,
53 NSDictionary<NSString *, UIImage *> *images)
54{
55 for (const auto &attachmentRange : attachmentRanges) {
56 if (attachmentRange.length == 0 || attachmentRange.location >= attributedString.length) {
57 continue;
58 }
59
60 NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
61 NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
62 UIImage *image = images[imageUri];
63 if ([imageUri hasPrefix:@"sf:"]) {
64 NSString *symbolName = [imageUri substringFromIndex:3];
65 UIColor *foregroundColor =
66 [attributedString attribute:NSForegroundColorAttributeName
67 atIndex:attachmentRange.location
68 effectiveRange:nil] ?: UIColor.labelColor;
69 image = [[UIImage systemImageNamed:symbolName] imageWithTintColor:foregroundColor
70 renderingMode:UIImageRenderingModeAlwaysOriginal];
71 }
72 attachment.image = image ?: [[UIImage alloc] init];
73 const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
74 attachment.bounds = CGRectMake(
75 0,
76 T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
77 attachmentSize,
78 attachmentSize);
79 const NSRange range = NSMakeRange(
80 attachmentRange.location,
81 MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
82 NSAttributedString *attachmentString =
83 [NSAttributedString attributedStringWithAttachment:attachment];
84 [attributedString replaceCharactersInRange:range withAttributedString:attachmentString];
85 }
86}
87
88@protocol T3MarkdownOutsideTapTarget <NSObject>
89- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
90@end
91
92@interface T3MarkdownOutsideTapCoordinator : NSObject <UIGestureRecognizerDelegate>
93
94- (instancetype)initWithWindow:(UIWindow *)window;
95- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target;
96- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target;
97
98@end
99
100static const void *T3MarkdownOutsideTapCoordinatorKey =
101 &T3MarkdownOutsideTapCoordinatorKey;
102
103@implementation T3MarkdownOutsideTapCoordinator {
104 __weak UIWindow *_window;
105 UITapGestureRecognizer *_recognizer;
106 NSHashTable<id<T3MarkdownOutsideTapTarget>> *_targets;
107}
108
109- (instancetype)initWithWindow:(UIWindow *)window
110{
111 if (self = [super init]) {
112 _window = window;
113 _targets = [NSHashTable weakObjectsHashTable];
114 _recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
115 action:@selector(handleTap:)];
116 _recognizer.cancelsTouchesInView = NO;
117 _recognizer.delegate = self;
118 [window addGestureRecognizer:_recognizer];
119 }
120 return self;
121}
122
123- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target
124{
125 [_targets addObject:target];
126}
127
128- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target
129{
130 [_targets removeObject:target];
131 if (_targets.count > 0) {
132 return;
133 }
134
135 UIWindow *window = _window;
136 [window removeGestureRecognizer:_recognizer];
137 if (objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey) == self) {
138 objc_setAssociatedObject(
139 window,
140 T3MarkdownOutsideTapCoordinatorKey,
141 nil,
142 OBJC_ASSOCIATION_RETAIN_NONATOMIC);
143 }
144}
145
146- (void)handleTap:(UITapGestureRecognizer *)sender
147{
148 UIWindow *window = _window;
149 if (window == nil) {
150 return;
151 }
152
153 UIView *hitView = [window hitTest:[sender locationInView:window] withEvent:nil];
154 if (hitView == nil) {
155 return;
156 }
157 for (id<T3MarkdownOutsideTapTarget> target in _targets.allObjects) {
158 [target clearSelectionForOutsideTapWithHitView:hitView];
159 }
160}
161
162- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
163 shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
164{
165 return YES;
166}
167
168@end
169
170static T3MarkdownOutsideTapCoordinator *
171T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
172{
173 T3MarkdownOutsideTapCoordinator *coordinator =
174 objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey);
175 if (coordinator == nil) {
176 coordinator = [[T3MarkdownOutsideTapCoordinator alloc] initWithWindow:window];
177 objc_setAssociatedObject(
178 window,
179 T3MarkdownOutsideTapCoordinatorKey,
180 coordinator,
181 OBJC_ASSOCIATION_RETAIN_NONATOMIC);
182 }
183 return coordinator;
184}
185
186@interface T3MarkdownText () <RCTT3MarkdownTextViewProtocol, UIGestureRecognizerDelegate, UITextViewDelegate>
187
188@end
189
190@interface T3MarkdownText () <T3MarkdownOutsideTapTarget>
191@end
192
193@implementation T3MarkdownText {
194 UIView * _view;
195 UITextView * _textView;
196 T3MarkdownTextShadowNode::ConcreteState::Shared _state;
197 __weak UIWindow * _outsideTapWindow;
198 BOOL _suppressSelectionChange;
199 NSMutableDictionary<NSString *, UIImage *> * _attachmentImages;
200 NSMutableSet<NSString *> * _pendingAttachmentUris;
201}
202
203+ (ComponentDescriptorProvider)componentDescriptorProvider
204{
205 return concreteComponentDescriptorProvider<T3MarkdownTextComponentDescriptor>();
206}
207
208- (instancetype)initWithFrame:(CGRect)frame
209{
210 if (self = [super initWithFrame:frame]) {
211 static const auto defaultProps = std::make_shared<const T3MarkdownTextProps>();
212 _props = defaultProps;
213
214 _view = [[UIView alloc] init];
215 self.contentView = _view;
216 self.clipsToBounds = true;
217
218 _textView = [[UITextView alloc] init];
219 _attachmentImages = [[NSMutableDictionary alloc] init];
220 _pendingAttachmentUris = [[NSMutableSet alloc] init];
221 _textView.scrollEnabled = false;
222 _textView.editable = false;
223 _textView.textContainerInset = UIEdgeInsetsZero;
224 _textView.textContainer.lineFragmentPadding = 0;
225 _textView.delegate = self;
226 // Must match RCTTextLayoutManager, which measures with usesFontLeading = NO.
227 _textView.layoutManager.usesFontLeading = NO;
228 [self addSubview:_textView];
229
230 const auto longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
231 action:@selector(handleLongPressIfNecessary:)];
232 longPressGestureRecognizer.delegate = self;
233
234 const auto pressGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
235 action:@selector(handlePressIfNecessary:)];
236 pressGestureRecognizer.delegate = self;
237 [pressGestureRecognizer requireGestureRecognizerToFail:longPressGestureRecognizer];
238
239 [_textView addGestureRecognizer:pressGestureRecognizer];
240 [_textView addGestureRecognizer:longPressGestureRecognizer];
241 }
242
243 return self;
244}
245
246- (void)didMoveToWindow
247{
248 [super didMoveToWindow];
249 if (_outsideTapWindow == self.window) {
250 return;
251 }
252 if (_outsideTapWindow != nil) {
253 T3MarkdownOutsideTapCoordinator *coordinator =
254 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
255 [coordinator removeTarget:self];
256 }
257 _outsideTapWindow = self.window;
258 if (_outsideTapWindow != nil) {
259 [T3MarkdownOutsideTapCoordinatorForWindow(_outsideTapWindow) addTarget:self];
260 }
261}
262
263- (void)dealloc
264{
265 T3MarkdownOutsideTapCoordinator *coordinator =
266 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
267 [coordinator removeTarget:self];
268}
269
270// See RCTParagraphComponentView
271- (void)prepareForRecycle
272{
273 [super prepareForRecycle];
274 T3MarkdownOutsideTapCoordinator *coordinator =
275 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
276 [coordinator removeTarget:self];
277 _outsideTapWindow = nil;
278 _state.reset();
279
280 // Reset the frame to zero so that when it properly lays out on the next use
281 _textView.frame = CGRectZero;
282 _textView.attributedText = nil;
283}
284
285- (void)layoutSubviews
286{
287 [super layoutSubviews];
288 // _textView's frame is assigned inside drawRect, which only fires when
289 // state changes. Trigger a redraw whenever the host frame moves out from
290 // under it (rotation, parent relayout) so the text view resizes and
291 // onTextLayout re-fires with the new line wrapping.
292 if (!CGRectEqualToRect(_textView.frame, _view.frame)) {
293 [self setNeedsDisplay];
294 }
295}
296
297- (void)drawRect:(CGRect)rect
298{
299 if (!_state) {
300 return;
301 }
302
303 const auto &props = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
304
305 const auto attrString = _state->getData().attributedString;
306 NSMutableAttributedString *convertedAttrString =
307 [RCTNSAttributedStringFromAttributedString(attrString) mutableCopy];
308 T3MarkdownTextApplyParagraphStyles(
309 convertedAttrString,
310 _state->getData().paragraphStyleRanges);
311 T3MarkdownTextApplyAttachments(
312 convertedAttrString,
313 _state->getData().attachmentRanges,
314 _attachmentImages);
315 [self loadAttachmentImages:_state->getData().attachmentRanges];
316
317 // Setting attributedText clears any active text selection, and re-assigning
318 // the frame triggers a layout flush that has the same effect. Bail out
319 // entirely when nothing actually changed so a JS-side state update made in
320 // response to onSelectionChange doesn't deselect what the user is selecting.
321 const BOOL textChanged = ![_textView.attributedText isEqualToAttributedString:convertedAttrString];
322 const BOOL frameChanged = !CGRectEqualToRect(_textView.frame, _view.frame);
323 if (!textChanged && !frameChanged) {
324 return;
325 }
326 if (textChanged) {
327 // Reassigning attributedText clears any active selection. Save it and
328 // restore after, while suppressing the synthetic textViewDidChangeSelection
329 // events the clear-then-restore would otherwise produce — those would
330 // round-trip to JS and re-trigger this same path, causing a loop.
331 const NSRange savedRange = _textView.selectedRange;
332 _suppressSelectionChange = YES;
333 _textView.attributedText = convertedAttrString;
334 if (savedRange.length > 0 && NSMaxRange(savedRange) <= _textView.attributedText.length) {
335 _textView.selectedRange = savedRange;
336 }
337 _suppressSelectionChange = NO;
338 }
339 if (frameChanged) {
340 _textView.frame = _view.frame;
341 }
342
343 __block std::vector<std::string> lines;
344 const int maxLines = props.numberOfLines;
345 [_textView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, convertedAttrString.string.length) usingBlock:^(CGRect rect,
346 CGRect usedRect,
347 NSTextContainer * _Nonnull textContainer,
348 NSRange glyphRange,
349 BOOL * _Nonnull stop) {
350 const auto charRange = [self->_textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
351 const auto line = [self->_textView.text substringWithRange:charRange];
352 lines.push_back(line.UTF8String);
353 // enumerateLineFragments overshoots maximumNumberOfLines by one on iOS
354 // 18, so cap explicitly.
355 if (maxLines > 0 && lines.size() >= (size_t)maxLines) {
356 *stop = YES;
357 }
358 }];
359
360 if (_eventEmitter != nullptr) {
361 std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
362 ->onTextLayout(facebook::react::T3MarkdownTextEventEmitter::OnTextLayout{static_cast<int>(self.tag), lines});
363 };
364}
365
366- (void)loadAttachmentImages:(const std::vector<T3MarkdownTextAttachmentRange> &)attachmentRanges
367{
368 for (const auto &attachmentRange : attachmentRanges) {
369 NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
370 if ([imageUri hasPrefix:@"sf:"]) {
371 continue;
372 }
373 if (_attachmentImages[imageUri] != nil || [_pendingAttachmentUris containsObject:imageUri]) {
374 continue;
375 }
376
377 NSURL *url = [NSURL URLWithString:imageUri];
378 if (url == nil) {
379 continue;
380 }
381 if (url.isFileURL) {
382 UIImage *image = [UIImage imageWithContentsOfFile:url.path];
383 if (image != nil) {
384 _attachmentImages[imageUri] = image;
385 dispatch_async(dispatch_get_main_queue(), ^{
386 [self refreshDisplayedAttachments];
387 });
388 }
389 continue;
390 }
391
392 [_pendingAttachmentUris addObject:imageUri];
393 [[[NSURLSession sharedSession] dataTaskWithURL:url
394 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
395 UIImage *image = data == nil ? nil : [UIImage imageWithData:data];
396 dispatch_async(dispatch_get_main_queue(), ^{
397 [self->_pendingAttachmentUris removeObject:imageUri];
398 if (image != nil) {
399 self->_attachmentImages[imageUri] = image;
400 [self refreshDisplayedAttachments];
401 }
402 });
403 }] resume];
404 }
405}
406
407- (void)refreshDisplayedAttachments
408{
409 if (!_state || _textView.attributedText == nil) {
410 return;
411 }
412
413 NSMutableAttributedString *attributedText = [_textView.attributedText mutableCopy];
414 T3MarkdownTextApplyAttachments(
415 attributedText,
416 _state->getData().attachmentRanges,
417 _attachmentImages);
418
419 const NSRange savedRange = _textView.selectedRange;
420 _suppressSelectionChange = YES;
421 _textView.attributedText = attributedText;
422 if (savedRange.location != NSNotFound &&
423 NSMaxRange(savedRange) <= _textView.attributedText.length) {
424 _textView.selectedRange = savedRange;
425 }
426 _suppressSelectionChange = NO;
427 [_textView setNeedsDisplay];
428}
429
430- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
431{
432 const auto &oldViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
433 const auto &newViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(props);
434
435 if (oldViewProps.numberOfLines != newViewProps.numberOfLines) {
436 _textView.textContainer.maximumNumberOfLines = newViewProps.numberOfLines;
437 }
438
439 if (oldViewProps.selectable != newViewProps.selectable) {
440 _textView.selectable = newViewProps.selectable;
441 }
442
443 if (oldViewProps.allowFontScaling != newViewProps.allowFontScaling) {
444 if (@available(iOS 11.0, *)) {
445 _textView.adjustsFontForContentSizeCategory = newViewProps.allowFontScaling;
446 }
447 }
448
449 if (oldViewProps.ellipsizeMode != newViewProps.ellipsizeMode) {
450 if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
451 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingHead;
452 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
453 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingMiddle;
454 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
455 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingTail;
456 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Clip) {
457 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByClipping;
458 }
459 }
460
461
462 // I'm not sure if this is really the right way to handle this style. This means that the entire _view_ the text
463 // is in will have this background color applied. To apply it just to a particular part of a string, you'd need
464 // to do <Text><Text style={{backgroundColor: 'blue'}}>Hello</Text></Text>.
465 // This is how the base <Text> component works though, so we'll go with it for now. Can change later if we want.
466 if (oldViewProps.backgroundColor != newViewProps.backgroundColor) {
467 _textView.backgroundColor = RCTUIColorFromSharedColor(newViewProps.backgroundColor);
468 }
469
470 [super updateProps:props oldProps:oldProps];
471}
472
473// See RCTParagraphComponentView
474- (void)updateState:(const facebook::react::State::Shared &)state oldState:(const facebook::react::State::Shared &)oldState
475{
476 _state = std::static_pointer_cast<const T3MarkdownTextShadowNode::ConcreteState>(state);
477 [self setNeedsDisplay];
478}
479
480// MARK: - UIGestureRecognizerDelegate
481
482- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
483{
484 return YES;
485}
486
487- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
488{
489 return YES;
490}
491
492- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView
493{
494 if ([hitView isDescendantOfView:self]) {
495 return;
496 }
497 // Defer past the current event loop turn so any in-flight edit-menu action
498 // (Copy / Define / Look Up / …) reads the live selection before we clear it.
499 UITextView *textView = _textView;
500 dispatch_async(dispatch_get_main_queue(), ^{
501 UITextRange *range = textView.selectedTextRange;
502 if (range != nil && !range.isEmpty) {
503 textView.selectedTextRange = nil;
504 }
505 });
506}
507
508// MARK: - Touch handling
509
510- (CGPoint)getLocationOfPress:(UIGestureRecognizer*)sender
511{
512 return [sender locationInView:_textView];
513}
514
515- (T3MarkdownTextRun*)getTouchChild:(CGPoint)location
516{
517 const auto charIndex = [_textView.layoutManager characterIndexForPoint:location
518 inTextContainer:_textView.textContainer
519 fractionOfDistanceBetweenInsertionPoints:nil
520 ];
521
522 int currIndex = -1;
523 for (UIView* child in self.subviews) {
524 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
525 continue;
526 }
527
528 T3MarkdownTextRun* textChild = (T3MarkdownTextRun*)child;
529
530 // This is UTF16 code units!!
531 currIndex += textChild.text.length;
532
533 if (charIndex <= currIndex) {
534 return textChild;
535 }
536 }
537
538 return nil;
539}
540
541- (void)handlePressIfNecessary:(UITapGestureRecognizer*)sender
542{
543 const auto location = [self getLocationOfPress:sender];
544 const auto child = [self getTouchChild:location];
545
546 if (child) {
547 [child onPress];
548 }
549}
550
551- (void)handleLongPressIfNecessary:(UILongPressGestureRecognizer*)sender
552{
553 const auto location = [self getLocationOfPress:sender];
554 const auto child = [self getTouchChild:location];
555
556 if (child) {
557 [child onLongPress];
558 }
559}
560
561// MARK: - UITextViewDelegate
562
563- (void)textViewDidChangeSelection:(UITextView *)textView
564{
565 if (_suppressSelectionChange) {
566 return;
567 }
568 if (_eventEmitter == nullptr) {
569 return;
570 }
571
572 const NSRange selectedRange = textView.selectedRange;
573 if (selectedRange.location == NSNotFound) {
574 return;
575 }
576
577 // Fires on programmatic selection changes too (e.g. the outside-tap clear
578 // in handleOutsideTap:), so JS will see a synthetic empty-range event then.
579 std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
580 ->onSelectionChange(facebook::react::T3MarkdownTextEventEmitter::OnSelectionChange{
581 static_cast<int>(self.tag),
582 static_cast<int>(selectedRange.location),
583 static_cast<int>(selectedRange.location + selectedRange.length),
584 });
585}
586
587Class<RCTComponentViewProtocol> T3MarkdownTextCls(void)
588{
589 return T3MarkdownText.class;
590}
591
592@end