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 UILongPressGestureRecognizer *_longPressGestureRecognizer;
202 UITapGestureRecognizer *_pressGestureRecognizer;
203}
204
205+ (ComponentDescriptorProvider)componentDescriptorProvider
206{
207 return concreteComponentDescriptorProvider<T3MarkdownTextComponentDescriptor>();
208}
209
210- (instancetype)initWithFrame:(CGRect)frame
211{
212 if (self = [super initWithFrame:frame]) {
213 static const auto defaultProps = std::make_shared<const T3MarkdownTextProps>();
214 _props = defaultProps;
215
216 _view = [[UIView alloc] init];
217 self.contentView = _view;
218 self.clipsToBounds = true;
219
220 _textView = [[UITextView alloc] init];
221 _attachmentImages = [[NSMutableDictionary alloc] init];
222 _pendingAttachmentUris = [[NSMutableSet alloc] init];
223 _textView.scrollEnabled = false;
224 _textView.editable = false;
225 _textView.textContainerInset = UIEdgeInsetsZero;
226 _textView.textContainer.lineFragmentPadding = 0;
227 _textView.delegate = self;
228 // Chat text supports selection and contextual actions, but not drag-and-drop.
229 _textView.textDragInteraction.enabled = NO;
230 _textView.linkTextAttributes = @{};
231 // Must match RCTTextLayoutManager, which measures with usesFontLeading = NO.
232 _textView.layoutManager.usesFontLeading = NO;
233 [self addSubview:_textView];
234
235 _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
236 action:@selector(handleLongPressIfNecessary:)];
237 _longPressGestureRecognizer.delegate = self;
238
239 _pressGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
240 action:@selector(handlePressIfNecessary:)];
241 _pressGestureRecognizer.delegate = self;
242 [_pressGestureRecognizer requireGestureRecognizerToFail:_longPressGestureRecognizer];
243
244 [_textView addGestureRecognizer:_pressGestureRecognizer];
245 [_textView addGestureRecognizer:_longPressGestureRecognizer];
246 }
247
248 return self;
249}
250
251- (void)didMoveToWindow
252{
253 [super didMoveToWindow];
254 if (_outsideTapWindow == self.window) {
255 return;
256 }
257 if (_outsideTapWindow != nil) {
258 T3MarkdownOutsideTapCoordinator *coordinator =
259 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
260 [coordinator removeTarget:self];
261 }
262 _outsideTapWindow = self.window;
263 if (_outsideTapWindow != nil) {
264 [T3MarkdownOutsideTapCoordinatorForWindow(_outsideTapWindow) addTarget:self];
265 }
266}
267
268- (void)dealloc
269{
270 T3MarkdownOutsideTapCoordinator *coordinator =
271 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
272 [coordinator removeTarget:self];
273}
274
275// See RCTParagraphComponentView
276- (void)prepareForRecycle
277{
278 [super prepareForRecycle];
279 T3MarkdownOutsideTapCoordinator *coordinator =
280 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
281 [coordinator removeTarget:self];
282 _outsideTapWindow = nil;
283 _state.reset();
284
285 // Reset the frame to zero so that when it properly lays out on the next use
286 _textView.frame = CGRectZero;
287 _textView.attributedText = nil;
288}
289
290- (void)layoutSubviews
291{
292 [super layoutSubviews];
293 // _textView's frame is assigned inside drawRect, which only fires when
294 // state changes. Trigger a redraw whenever the host frame moves out from
295 // under it (rotation, parent relayout) so the text view resizes and
296 // onTextLayout re-fires with the new line wrapping.
297 if (!CGRectEqualToRect(_textView.frame, _view.frame)) {
298 [self setNeedsDisplay];
299 }
300}
301
302- (void)drawRect:(CGRect)rect
303{
304 if (!_state) {
305 return;
306 }
307
308 const auto &props = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
309
310 const auto attrString = _state->getData().attributedString;
311 NSMutableAttributedString *convertedAttrString =
312 [RCTNSAttributedStringFromAttributedString(attrString) mutableCopy];
313 T3MarkdownTextApplyParagraphStyles(
314 convertedAttrString,
315 _state->getData().paragraphStyleRanges);
316 T3MarkdownTextApplyAttachments(
317 convertedAttrString,
318 _state->getData().attachmentRanges,
319 _attachmentImages);
320 NSUInteger runLocation = 0;
321 for (UIView *child in self.subviews) {
322 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
323 continue;
324 }
325
326 T3MarkdownTextRun *textChild = (T3MarkdownTextRun *)child;
327 const NSRange runRange = NSMakeRange(runLocation, textChild.text.length);
328 runLocation = NSMaxRange(runRange);
329 if (![textChild hasContextMenu] || runRange.length == 0 ||
330 NSMaxRange(runRange) > convertedAttrString.length) {
331 continue;
332 }
333
334 NSURL *link = [NSURL URLWithString:
335 [NSString stringWithFormat:@"t3-markdown-run://%ld", (long)textChild.tag]];
336 if (link != nil) {
337 [convertedAttrString addAttribute:NSLinkAttributeName value:link range:runRange];
338 }
339 }
340 [self loadAttachmentImages:_state->getData().attachmentRanges];
341
342 // Setting attributedText clears any active text selection, and re-assigning
343 // the frame triggers a layout flush that has the same effect. Bail out
344 // entirely when nothing actually changed so a JS-side state update made in
345 // response to onSelectionChange doesn't deselect what the user is selecting.
346 const BOOL textChanged = ![_textView.attributedText isEqualToAttributedString:convertedAttrString];
347 const BOOL frameChanged = !CGRectEqualToRect(_textView.frame, _view.frame);
348 if (!textChanged && !frameChanged) {
349 return;
350 }
351 if (textChanged) {
352 // Reassigning attributedText clears any active selection. Save it and
353 // restore after, while suppressing the synthetic textViewDidChangeSelection
354 // events the clear-then-restore would otherwise produce — those would
355 // round-trip to JS and re-trigger this same path, causing a loop.
356 const NSRange savedRange = _textView.selectedRange;
357 _suppressSelectionChange = YES;
358 _textView.attributedText = convertedAttrString;
359 if (savedRange.length > 0 && NSMaxRange(savedRange) <= _textView.attributedText.length) {
360 _textView.selectedRange = savedRange;
361 }
362 _suppressSelectionChange = NO;
363 }
364 if (frameChanged) {
365 _textView.frame = _view.frame;
366 }
367
368 __block std::vector<std::string> lines;
369 const int maxLines = props.numberOfLines;
370 [_textView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, convertedAttrString.string.length) usingBlock:^(CGRect rect,
371 CGRect usedRect,
372 NSTextContainer * _Nonnull textContainer,
373 NSRange glyphRange,
374 BOOL * _Nonnull stop) {
375 const auto charRange = [self->_textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
376 const auto line = [self->_textView.text substringWithRange:charRange];
377 lines.push_back(line.UTF8String);
378 // enumerateLineFragments overshoots maximumNumberOfLines by one on iOS
379 // 18, so cap explicitly.
380 if (maxLines > 0 && lines.size() >= (size_t)maxLines) {
381 *stop = YES;
382 }
383 }];
384
385 if (_eventEmitter != nullptr) {
386 std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
387 ->onTextLayout(facebook::react::T3MarkdownTextEventEmitter::OnTextLayout{static_cast<int>(self.tag), lines});
388 };
389}
390
391- (void)loadAttachmentImages:(const std::vector<T3MarkdownTextAttachmentRange> &)attachmentRanges
392{
393 for (const auto &attachmentRange : attachmentRanges) {
394 NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
395 if ([imageUri hasPrefix:@"sf:"]) {
396 continue;
397 }
398 if (_attachmentImages[imageUri] != nil || [_pendingAttachmentUris containsObject:imageUri]) {
399 continue;
400 }
401
402 NSURL *url = [NSURL URLWithString:imageUri];
403 if (url == nil) {
404 continue;
405 }
406 if (url.isFileURL) {
407 UIImage *image = [UIImage imageWithContentsOfFile:url.path];
408 if (image != nil) {
409 _attachmentImages[imageUri] = image;
410 dispatch_async(dispatch_get_main_queue(), ^{
411 [self refreshDisplayedAttachments];
412 });
413 }
414 continue;
415 }
416
417 [_pendingAttachmentUris addObject:imageUri];
418 [[[NSURLSession sharedSession] dataTaskWithURL:url
419 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
420 UIImage *image = data == nil ? nil : [UIImage imageWithData:data];
421 dispatch_async(dispatch_get_main_queue(), ^{
422 [self->_pendingAttachmentUris removeObject:imageUri];
423 if (image != nil) {
424 self->_attachmentImages[imageUri] = image;
425 [self refreshDisplayedAttachments];
426 }
427 });
428 }] resume];
429 }
430}
431
432- (void)refreshDisplayedAttachments
433{
434 if (!_state || _textView.attributedText == nil) {
435 return;
436 }
437
438 NSMutableAttributedString *attributedText = [_textView.attributedText mutableCopy];
439 T3MarkdownTextApplyAttachments(
440 attributedText,
441 _state->getData().attachmentRanges,
442 _attachmentImages);
443
444 const NSRange savedRange = _textView.selectedRange;
445 _suppressSelectionChange = YES;
446 _textView.attributedText = attributedText;
447 if (savedRange.location != NSNotFound &&
448 NSMaxRange(savedRange) <= _textView.attributedText.length) {
449 _textView.selectedRange = savedRange;
450 }
451 _suppressSelectionChange = NO;
452 [_textView setNeedsDisplay];
453}
454
455- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
456{
457 const auto &oldViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
458 const auto &newViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(props);
459
460 if (oldViewProps.numberOfLines != newViewProps.numberOfLines) {
461 _textView.textContainer.maximumNumberOfLines = newViewProps.numberOfLines;
462 }
463
464 if (oldViewProps.selectable != newViewProps.selectable) {
465 _textView.selectable = newViewProps.selectable;
466 }
467
468 if (oldViewProps.allowFontScaling != newViewProps.allowFontScaling) {
469 if (@available(iOS 11.0, *)) {
470 _textView.adjustsFontForContentSizeCategory = newViewProps.allowFontScaling;
471 }
472 }
473
474 if (oldViewProps.ellipsizeMode != newViewProps.ellipsizeMode) {
475 if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
476 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingHead;
477 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
478 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingMiddle;
479 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
480 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingTail;
481 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Clip) {
482 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByClipping;
483 }
484 }
485
486
487 // I'm not sure if this is really the right way to handle this style. This means that the entire _view_ the text
488 // is in will have this background color applied. To apply it just to a particular part of a string, you'd need
489 // to do <Text><Text style={{backgroundColor: 'blue'}}>Hello</Text></Text>.
490 // This is how the base <Text> component works though, so we'll go with it for now. Can change later if we want.
491 if (oldViewProps.backgroundColor != newViewProps.backgroundColor) {
492 _textView.backgroundColor = RCTUIColorFromSharedColor(newViewProps.backgroundColor);
493 }
494
495 [super updateProps:props oldProps:oldProps];
496}
497
498// See RCTParagraphComponentView
499- (void)updateState:(const facebook::react::State::Shared &)state oldState:(const facebook::react::State::Shared &)oldState
500{
501 _state = std::static_pointer_cast<const T3MarkdownTextShadowNode::ConcreteState>(state);
502 [self setNeedsDisplay];
503}
504
505// MARK: - UIGestureRecognizerDelegate
506
507- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
508{
509 return YES;
510}
511
512- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
513{
514 if (gestureRecognizer != _longPressGestureRecognizer &&
515 gestureRecognizer != _pressGestureRecognizer) {
516 return YES;
517 }
518
519 const auto location = [self getLocationOfPress:gestureRecognizer];
520 const auto child = [self getTouchChild:location];
521 return ![child hasContextMenu];
522}
523
524- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
525{
526 return YES;
527}
528
529- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView
530{
531 if ([hitView isDescendantOfView:self]) {
532 return;
533 }
534 // Defer past the current event loop turn so any in-flight edit-menu action
535 // (Copy / Define / Look Up / …) reads the live selection before we clear it.
536 UITextView *textView = _textView;
537 dispatch_async(dispatch_get_main_queue(), ^{
538 UITextRange *range = textView.selectedTextRange;
539 if (range != nil && !range.isEmpty) {
540 textView.selectedTextRange = nil;
541 }
542 });
543}
544
545// MARK: - Touch handling
546
547- (nullable T3MarkdownTextRun *)childForCharacterRange:(NSRange)characterRange
548{
549 NSUInteger location = 0;
550 for (UIView *child in self.subviews) {
551 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
552 continue;
553 }
554
555 T3MarkdownTextRun *textChild = (T3MarkdownTextRun *)child;
556 const NSRange range = NSMakeRange(location, textChild.text.length);
557 if (NSIntersectionRange(range, characterRange).length > 0) {
558 return textChild;
559 }
560 location = NSMaxRange(range);
561 }
562 return nil;
563}
564
565- (CGPoint)getLocationOfPress:(UIGestureRecognizer*)sender
566{
567 return [sender locationInView:_textView];
568}
569
570- (T3MarkdownTextRun*)getTouchChild:(CGPoint)location
571{
572 const auto charIndex = [_textView.layoutManager characterIndexForPoint:location
573 inTextContainer:_textView.textContainer
574 fractionOfDistanceBetweenInsertionPoints:nil
575 ];
576
577 int currIndex = -1;
578 for (UIView* child in self.subviews) {
579 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
580 continue;
581 }
582
583 T3MarkdownTextRun* textChild = (T3MarkdownTextRun*)child;
584
585 // This is UTF16 code units!!
586 currIndex += textChild.text.length;
587
588 if (charIndex <= currIndex) {
589 return textChild;
590 }
591 }
592
593 return nil;
594}
595
596- (void)handlePressIfNecessary:(UITapGestureRecognizer*)sender
597{
598 const auto location = [self getLocationOfPress:sender];
599 const auto child = [self getTouchChild:location];
600
601 if (child) {
602 [child onPress];
603 }
604}
605
606- (void)handleLongPressIfNecessary:(UILongPressGestureRecognizer*)sender
607{
608 if (sender.state != UIGestureRecognizerStateBegan) {
609 return;
610 }
611
612 const auto location = [self getLocationOfPress:sender];
613 const auto child = [self getTouchChild:location];
614
615 if (child) {
616 [child onLongPress];
617 }
618}
619
620// MARK: - UITextViewDelegate
621
622- (nullable UIAction *)textView:(UITextView *)textView
623 primaryActionForTextItem:(UITextItem *)textItem
624 defaultAction:(UIAction *)defaultAction API_AVAILABLE(ios(17.0))
625{
626 T3MarkdownTextRun *child = [self childForCharacterRange:textItem.range];
627 if (![child hasContextMenu]) {
628 return defaultAction;
629 }
630
631 __weak T3MarkdownTextRun *weakChild = child;
632 return [UIAction actionWithHandler:^(__kindof UIAction *action) {
633 [weakChild onPress];
634 }];
635}
636
637- (nullable UITextItemMenuConfiguration *)textView:(UITextView *)textView
638 menuConfigurationForTextItem:(UITextItem *)textItem
639 defaultMenu:(UIMenu *)defaultMenu API_AVAILABLE(ios(17.0))
640{
641 T3MarkdownTextRun *child = [self childForCharacterRange:textItem.range];
642 UIMenu *menu = [child contextMenu];
643 return [UITextItemMenuConfiguration configurationWithMenu:menu ?: defaultMenu];
644}
645
646- (void)textViewDidChangeSelection:(UITextView *)textView
647{
648 if (_suppressSelectionChange) {
649 return;
650 }
651 if (_eventEmitter == nullptr) {
652 return;
653 }
654
655 const NSRange selectedRange = textView.selectedRange;
656 if (selectedRange.location == NSNotFound) {
657 return;
658 }
659
660 // Fires on programmatic selection changes too (e.g. the outside-tap clear
661 // in handleOutsideTap:), so JS will see a synthetic empty-range event then.
662 std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
663 ->onSelectionChange(facebook::react::T3MarkdownTextEventEmitter::OnSelectionChange{
664 static_cast<int>(self.tag),
665 static_cast<int>(selectedRange.location),
666 static_cast<int>(selectedRange.location + selectedRange.length),
667 });
668}
669
670Class<RCTComponentViewProtocol> T3MarkdownTextCls(void)
671{
672 return T3MarkdownText.class;
673}
674
675@end