Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

T3MarkdownText.mm

829 lines31.7 KB

1#import "T3MarkdownText.h"
2#import "T3MarkdownTextShadowNode.h"
3#import "T3MarkdownTextComponentDescriptor.h"
4#import "T3MarkdownTextRun.h"
5#import "T3ContextChip.h"
6#import <React/RCTConversions.h>
7#import <objc/runtime.h>
8​
9#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
10#import <react/renderer/components/T3MarkdownTextSpec/EventEmitters.h>
11#import <react/renderer/components/T3MarkdownTextSpec/Props.h>
12#import <react/renderer/components/T3MarkdownTextSpec/RCTComponentViewHelpers.h>
13#import <React/RCTFabricComponentsPlugins.h>
14​
15using namespace facebook::react;
16​
17@interface T3ContextChipAccessibilityElement : UIAccessibilityElement
18@property(nonatomic, weak) T3MarkdownTextRun *run;
19@end
20​
21@implementation T3ContextChipAccessibilityElement
22- (BOOL)accessibilityActivate
24 if (self.run == nil) return NO;
25 [self.run onPress];
26 return YES;
28@end
29​
30/** Preserve canonical references and their payload when copying a native text selection. */
31@interface T3ContextCopyTextView : UITextView
32@property(nonatomic, copy) NSDictionary *contextClipboardConfig;
33@end
34​
35@implementation T3ContextCopyTextView
36// Read-only text still supports selecting the entire document after selecting a word.
37- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
39 if (action == @selector(selectAll:)) {
40 return self.selectable && self.text.length > 0 && self.selectedRange.length < self.text.length;
41 }
42 return [super canPerformAction:action withSender:sender];
44​
45- (void)copy:(id)sender
47 NSRange selected = self.selectedRange;
48 NSArray *ranges = self.contextClipboardConfig[@"ranges"];
49 if (selected.location == NSNotFound || selected.length == 0 || NSMaxRange(selected) > self.text.length || ranges.count == 0) {
50 [super copy:sender];
51 return;
52 }
53 NSMutableString *text = [[self.text substringWithRange:selected] mutableCopy];
54 BOOL hasContext = NO;
55 for (NSDictionary *range in [ranges reverseObjectEnumerator]) {
56 NSUInteger start = [range[@"start"] unsignedIntegerValue];
57 NSUInteger end = [range[@"end"] unsignedIntegerValue];
58 if (end <= start || end > self.text.length) continue;
59 NSRange overlap = NSIntersectionRange(selected, NSMakeRange(start, end - start));
60 if (overlap.length == 0 || ![range[@"text"] isKindOfClass:NSString.class]) continue;
61 [text replaceCharactersInRange:NSMakeRange(overlap.location - selected.location, overlap.length) withString:range[@"text"]];
62 hasContext = YES;
63 }
64 if (!hasContext) { [super copy:sender]; return; }
65 [text replaceOccurrencesOfString:@"\uFFFC\u00A0" withString:@"" options:0 range:NSMakeRange(0, text.length)];
66 NSString *fragment = self.contextClipboardConfig[@"fragment"];
67 NSMutableDictionary *payload = [[NSJSONSerialization JSONObjectWithData:[fragment dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil] mutableCopy];
68 NSArray *records = payload[@"records"];
69 NSMutableArray *copied = [NSMutableArray array];
70 NSMutableSet *screenshots = [NSMutableSet set];
71 for (NSDictionary *record in records) {
72 if ([text containsString:[NSString stringWithFormat:@"/%@)", record[@"contextId"]]]) {
73 [copied addObject:record];
74 if ([record[@"screenshotContextId"] isKindOfClass:NSString.class]) [screenshots addObject:record[@"screenshotContextId"]];
75 }
76 }
77 for (NSDictionary *record in records) {
78 if ([screenshots containsObject:record[@"contextId"]] && ![copied containsObject:record]) [copied addObject:record];
79 }
80 payload[@"records"] = copied;
81 NSData *encoded = payload ? [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil] : nil;
82 NSMutableDictionary *item = [@{@"public.utf8-plain-text": text} mutableCopy];
83 if (encoded && copied.count > 0) {
84 NSString *raw = [[NSString alloc] initWithData:encoded encoding:NSUTF8StringEncoding];
85 NSString *attribute = [raw stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.alphanumericCharacterSet];
86 NSString *escaped = [[[text stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"] stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"] stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
87 item[@"app.t3.context-fragment"] = encoded;
88 item[@"public.html"] = [[NSString stringWithFormat:@"<pre data-t3-context-fragment=\"%@\">%@</pre>", attribute, escaped] dataUsingEncoding:NSUTF8StringEncoding];
89 }
90 UIPasteboard.generalPasteboard.items = @[item];
92@end
93​
94static void T3MarkdownTextApplyParagraphStyles(
95 NSMutableAttributedString *attributedString,
96 const std::vector<T3MarkdownTextParagraphStyleRange> &styleRanges)
98 for (const auto &styleRange : styleRanges) {
99 if (styleRange.length == 0 || styleRange.location >= attributedString.length) {
100 continue;
101 }
102​
103 const NSRange markerRange = NSMakeRange(
104 styleRange.location,
105 MIN(styleRange.length, attributedString.length - styleRange.location));
106 const NSRange paragraphRange = [attributedString.string paragraphRangeForRange:markerRange];
107 const NSParagraphStyle *existingStyle =
108 [attributedString attribute:NSParagraphStyleAttributeName
109 atIndex:paragraphRange.location
110 effectiveRange:nil];
111 NSMutableParagraphStyle *paragraphStyle =
112 existingStyle ? [existingStyle mutableCopy] : [NSMutableParagraphStyle new];
113 paragraphStyle.firstLineHeadIndent = styleRange.firstLineHeadIndent;
114 paragraphStyle.headIndent = styleRange.headIndent;
115 paragraphStyle.paragraphSpacing = styleRange.paragraphSpacing;
116 paragraphStyle.tabStops = @[
117 [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft
118 location:styleRange.headIndent
119 options:@{}]
120 ];
121 paragraphStyle.defaultTabInterval = styleRange.headIndent;
122 [attributedString addAttribute:NSParagraphStyleAttributeName
123 value:paragraphStyle
124 range:paragraphRange];
125 }
127​
128static void T3MarkdownTextApplyAttachments(
129 NSMutableAttributedString *attributedString,
130 const std::vector<T3MarkdownTextAttachmentRange> &attachmentRanges,
131 NSDictionary<NSString *, UIImage *> *images)
133 for (const auto &attachmentRange : attachmentRanges) {
134 if (attachmentRange.length == 0 || attachmentRange.location >= attributedString.length) {
135 continue;
136 }
137​
138 NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
139 NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
140 UIImage *image = images[imageUri];
141 const BOOL isSymbol = [imageUri hasPrefix:@"sf:"];
142 if (isSymbol) {
143 image = [UIImage systemImageNamed:[imageUri substringFromIndex:3]];
144 }
145 NSDictionary *runAttributes =
146 [attributedString attributesAtIndex:attachmentRange.location effectiveRange:nil];
147 UIColor *foregroundColor = runAttributes[NSForegroundColorAttributeName];
148 if (image != nil && (isSymbol || attachmentRange.tintWithForeground)) {
149 image = [image imageWithTintColor:foregroundColor ?: UIColor.labelColor
150 renderingMode:UIImageRenderingModeAlwaysOriginal];
151 }
152 attachment.image = image ?: [[UIImage alloc] init];
153 const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
154 attachment.bounds = CGRectMake(
155 0,
156 T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
157 attachmentSize,
158 attachmentSize);
159 NSDictionary *chip = T3ContextChipPayload(imageUri);
160 if (chip != nil) {
161 CGSize size = CGSizeMake(attachmentRange.chipWidth, attachmentRange.chipHeight);
162 attachment.bounds = T3ContextChipBounds(runAttributes[NSFontAttributeName], size);
163 NSString *iconUri = [chip[@"iconUri"] isKindOfClass:NSString.class] ? chip[@"iconUri"] : nil;
164 attachment.image = T3ContextChipImage(chip, size, iconUri ? images[iconUri] : nil);
165 }
166 const NSRange range = NSMakeRange(
167 attachmentRange.location,
168 MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
169 [attributedString replaceCharactersInRange:range
170 withAttributedString:T3MarkdownTextAttachmentString(attachment, runAttributes)];
171 }
173​
174@protocol T3MarkdownOutsideTapTarget <NSObject>
175- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
176@end
177​
178@interface T3MarkdownOutsideTapCoordinator : NSObject <UIGestureRecognizerDelegate>
179​
180- (instancetype)initWithWindow:(UIWindow *)window;
181- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target;
182- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target;
183​
184@end
185​
186static const void *T3MarkdownOutsideTapCoordinatorKey =
187 &T3MarkdownOutsideTapCoordinatorKey;
188​
189@implementation T3MarkdownOutsideTapCoordinator {
190 __weak UIWindow *_window;
191 UITapGestureRecognizer *_recognizer;
192 NSHashTable<id<T3MarkdownOutsideTapTarget>> *_targets;
194​
195- (instancetype)initWithWindow:(UIWindow *)window
197 if (self = [super init]) {
198 _window = window;
199 _targets = [NSHashTable weakObjectsHashTable];
200 _recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
201 action:@selector(handleTap:)];
202 _recognizer.cancelsTouchesInView = NO;
203 _recognizer.delegate = self;
204 [window addGestureRecognizer:_recognizer];
205 }
206 return self;
208​
209- (void)addTarget:(id<T3MarkdownOutsideTapTarget>)target
211 [_targets addObject:target];
213​
214- (void)removeTarget:(id<T3MarkdownOutsideTapTarget>)target
216 [_targets removeObject:target];
217 if (_targets.count > 0) {
218 return;
219 }
220​
221 UIWindow *window = _window;
222 [window removeGestureRecognizer:_recognizer];
223 if (objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey) == self) {
224 objc_setAssociatedObject(
225 window,
226 T3MarkdownOutsideTapCoordinatorKey,
227 nil,
228 OBJC_ASSOCIATION_RETAIN_NONATOMIC);
229 }
231​
232- (void)handleTap:(UITapGestureRecognizer *)sender
234 UIWindow *window = _window;
235 if (window == nil) {
236 return;
237 }
238​
239 UIView *hitView = [window hitTest:[sender locationInView:window] withEvent:nil];
240 if (hitView == nil) {
241 return;
242 }
243 for (id<T3MarkdownOutsideTapTarget> target in _targets.allObjects) {
244 [target clearSelectionForOutsideTapWithHitView:hitView];
245 }
247​
248- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
249 shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
251 return YES;
253​
254@end
255​
256static T3MarkdownOutsideTapCoordinator *
257T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
259 T3MarkdownOutsideTapCoordinator *coordinator =
260 objc_getAssociatedObject(window, T3MarkdownOutsideTapCoordinatorKey);
261 if (coordinator == nil) {
262 coordinator = [[T3MarkdownOutsideTapCoordinator alloc] initWithWindow:window];
263 objc_setAssociatedObject(
264 window,
265 T3MarkdownOutsideTapCoordinatorKey,
266 coordinator,
267 OBJC_ASSOCIATION_RETAIN_NONATOMIC);
268 }
269 return coordinator;
271​
272@interface T3MarkdownText () <RCTT3MarkdownTextViewProtocol, UIGestureRecognizerDelegate, UITextViewDelegate>
273​
274@end
275​
276@interface T3MarkdownText () <T3MarkdownOutsideTapTarget>
277@end
278​
279@implementation T3MarkdownText {
280 UIView * _view;
281 T3ContextCopyTextView * _textView;
282 T3MarkdownTextShadowNode::ConcreteState::Shared _state;
283 __weak UIWindow * _outsideTapWindow;
284 BOOL _suppressSelectionChange;
285 NSMutableDictionary<NSString *, UIImage *> * _attachmentImages;
286 NSMutableSet<NSString *> * _pendingAttachmentUris;
287 UILongPressGestureRecognizer *_longPressGestureRecognizer;
288 UITapGestureRecognizer *_pressGestureRecognizer;
289 NSArray *_contextAccessibilityElements;
291​
292+ (ComponentDescriptorProvider)componentDescriptorProvider
294 return concreteComponentDescriptorProvider<T3MarkdownTextComponentDescriptor>();
296​
297- (instancetype)initWithFrame:(CGRect)frame
299 if (self = [super initWithFrame:frame]) {
300 static const auto defaultProps = std::make_shared<const T3MarkdownTextProps>();
301 _props = defaultProps;
302​
303 _view = [[UIView alloc] init];
304 self.contentView = _view;
305 self.clipsToBounds = true;
306​
307 _textView = [[T3ContextCopyTextView alloc] init];
308 _attachmentImages = [[NSMutableDictionary alloc] init];
309 _pendingAttachmentUris = [[NSMutableSet alloc] init];
310 _textView.scrollEnabled = false;
311 _textView.editable = false;
312 _textView.textContainerInset = UIEdgeInsetsZero;
313 _textView.textContainer.lineFragmentPadding = 0;
314 _textView.delegate = self;
315 // Chat text supports selection and contextual actions, but not drag-and-drop.
316 _textView.textDragInteraction.enabled = NO;
317 _textView.linkTextAttributes = @{};
318 // Must match RCTTextLayoutManager, which measures with usesFontLeading = NO.
319 _textView.layoutManager.usesFontLeading = NO;
320 [self addSubview:_textView];
321​
322 _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
323 action:@selector(handleLongPressIfNecessary:)];
324 _longPressGestureRecognizer.delegate = self;
325​
326 _pressGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
327 action:@selector(handlePressIfNecessary:)];
328 _pressGestureRecognizer.delegate = self;
329 [_pressGestureRecognizer requireGestureRecognizerToFail:_longPressGestureRecognizer];
330​
331 [_textView addGestureRecognizer:_pressGestureRecognizer];
332 [_textView addGestureRecognizer:_longPressGestureRecognizer];
333 }
334​
335 return self;
337​
338- (void)didMoveToWindow
340 [super didMoveToWindow];
341 if (_outsideTapWindow == self.window) {
342 return;
343 }
344 if (_outsideTapWindow != nil) {
345 T3MarkdownOutsideTapCoordinator *coordinator =
346 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
347 [coordinator removeTarget:self];
348 }
349 _outsideTapWindow = self.window;
350 if (_outsideTapWindow != nil) {
351 [T3MarkdownOutsideTapCoordinatorForWindow(_outsideTapWindow) addTarget:self];
352 }
354​
355- (void)dealloc
357 T3MarkdownOutsideTapCoordinator *coordinator =
358 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
359 [coordinator removeTarget:self];
361​
362- (NSArray *)accessibilityElements
364 return _contextAccessibilityElements ?: [super accessibilityElements];
366​
367// See RCTParagraphComponentView
368- (void)prepareForRecycle
370 [super prepareForRecycle];
371 T3MarkdownOutsideTapCoordinator *coordinator =
372 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
373 [coordinator removeTarget:self];
374 _outsideTapWindow = nil;
375 _state.reset();
376​
377 // Reset the frame to zero so that when it properly lays out on the next use
378 _textView.frame = CGRectZero;
379 _textView.attributedText = nil;
380 _contextAccessibilityElements = nil;
382​
383- (void)layoutSubviews
385 [super layoutSubviews];
386 // _textView's frame is assigned inside drawRect, which only fires when
387 // state changes. Trigger a redraw whenever the host frame moves out from
388 // under it (rotation, parent relayout) so the text view resizes and
389 // onTextLayout re-fires with the new line wrapping.
390 if (!CGRectEqualToRect(_textView.frame, _view.frame)) {
391 [self setNeedsDisplay];
392 }
394​
395- (void)drawRect:(CGRect)rect
397 if (!_state) {
398 return;
399 }
400​
401 const auto &props = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
402​
403 const auto attrString = _state->getData().attributedString;
404 NSMutableAttributedString *convertedAttrString =
405 [RCTNSAttributedStringFromAttributedString(attrString) mutableCopy];
406 T3MarkdownTextApplyParagraphStyles(
407 convertedAttrString,
408 _state->getData().paragraphStyleRanges);
409 T3MarkdownTextApplyAttachments(
410 convertedAttrString,
411 _state->getData().attachmentRanges,
412 _attachmentImages);
413 // Matches the shadow node so drawn lines sit where measurement put them.
414 RCTApplyBaselineOffset(convertedAttrString);
415 NSUInteger runLocation = 0;
416 for (UIView *child in self.subviews) {
417 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
418 continue;
419 }
420​
421 T3MarkdownTextRun *textChild = (T3MarkdownTextRun *)child;
422 const NSRange runRange = NSMakeRange(runLocation, textChild.text.length);
423 runLocation = NSMaxRange(runRange);
424 if (![textChild hasContextMenu] || runRange.length == 0 ||
425 NSMaxRange(runRange) > convertedAttrString.length) {
426 continue;
427 }
428​
429 NSURL *link = [NSURL URLWithString:
430 [NSString stringWithFormat:@"t3-markdown-run://%ld", (long)textChild.tag]];
431 if (link != nil) {
432 // A glyph must not be both a link and an attachment. UIKit caches them as
433 // different text-item classes and can send `attachment` to a cached link
434 // on a later tap. Attachment actions already use primaryActionForTextItem.
435 [convertedAttrString enumerateAttribute:NSAttachmentAttributeName
436 inRange:runRange
437 options:0
438 usingBlock:^(id attachment, NSRange range, BOOL *stop) {
439 if (attachment == nil) {
440 [convertedAttrString addAttribute:NSLinkAttributeName value:link range:range];
441 }
442 }];
443 }
444 }
445 [self loadAttachmentImages:_state->getData().attachmentRanges];
446​
447 // Setting attributedText clears any active text selection, and re-assigning
448 // the frame triggers a layout flush that has the same effect. Bail out
449 // entirely when nothing actually changed so a JS-side state update made in
450 // response to onSelectionChange doesn't deselect what the user is selecting.
451 const BOOL textChanged = ![_textView.attributedText isEqualToAttributedString:convertedAttrString];
452 const BOOL frameChanged = !CGRectEqualToRect(_textView.frame, _view.frame);
453 if (!textChanged && !frameChanged) {
454 return;
455 }
456 if (textChanged) {
457 // Reassigning attributedText clears any active selection. Save it and
458 // restore after, while suppressing the synthetic textViewDidChangeSelection
459 // events the clear-then-restore would otherwise produce — those would
460 // round-trip to JS and re-trigger this same path, causing a loop.
461 const NSRange savedRange = _textView.selectedRange;
462 _suppressSelectionChange = YES;
463 _textView.attributedText = convertedAttrString;
464 NSMutableString *accessibleText = [convertedAttrString.string mutableCopy];
465 for (auto it = _state->getData().attachmentRanges.rbegin();
466 it != _state->getData().attachmentRanges.rend(); ++it) {
467 NSDictionary *chip = T3ContextChipPayload([NSString stringWithUTF8String:it->imageUri.c_str()]);
468 if (chip != nil && it->location < accessibleText.length) {
469 [accessibleText replaceCharactersInRange:NSMakeRange(it->location, 1) withString:chip[@"label"]];
470 }
471 }
472 _textView.accessibilityLabel = accessibleText;
473 if (savedRange.length > 0 && NSMaxRange(savedRange) <= _textView.attributedText.length) {
474 _textView.selectedRange = savedRange;
475 }
476 _suppressSelectionChange = NO;
477 }
478 if (frameChanged) {
479 _textView.frame = _view.frame;
480 }
481​
482 // Text attachments have no native link element. Expose their existing runs
483 // at the measured glyph bounds, without inserting views into text layout.
484 NSMutableArray *accessibleElements = [NSMutableArray arrayWithObject:_textView];
485 for (UIView *child in self.subviews) {
486 if (![child isKindOfClass:T3MarkdownTextRun.class]) continue;
487 T3MarkdownTextRun *run = (T3MarkdownTextRun *)child;
488 run.contextChipInteractive = NO;
489 }
490 for (const auto &attachmentRange : _state->getData().attachmentRanges) {
491 NSDictionary *chip = T3ContextChipPayload(
492 [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()]);
493 if (![chip[@"interactive"] boolValue]) continue;
494 NSRange range = NSMakeRange(attachmentRange.location, 1);
495 T3MarkdownTextRun *run = [self childForCharacterRange:range];
496 if (!run || NSMaxRange(range) > convertedAttrString.length) continue;
497 NSRange glyphRange = [_textView.layoutManager glyphRangeForCharacterRange:range actualCharacterRange:nil];
498 CGRect bounds = [_textView.layoutManager boundingRectForGlyphRange:glyphRange
499 inTextContainer:_textView.textContainer];
500 bounds = CGRectOffset(bounds, _textView.textContainerInset.left, _textView.textContainerInset.top);
501 run.contextChipInteractive = YES;
502 T3ContextChipAccessibilityElement *element =
503 [[T3ContextChipAccessibilityElement alloc] initWithAccessibilityContainer:self];
504 element.run = run;
505 element.accessibilityLabel = chip[@"label"];
506 element.accessibilityTraits = UIAccessibilityTraitButton;
507 element.accessibilityFrameInContainerSpace = [_textView convertRect:bounds toView:self];
508 [accessibleElements addObject:element];
509 }
510 _contextAccessibilityElements = accessibleElements;
511​
512 __block std::vector<std::string> lines;
513 const int maxLines = props.numberOfLines;
514 [_textView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, convertedAttrString.string.length) usingBlock:^(CGRect rect,
515 CGRect usedRect,
516 NSTextContainer * _Nonnull textContainer,
517 NSRange glyphRange,
518 BOOL * _Nonnull stop) {
519 const auto charRange = [self->_textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
520 const auto line = [self->_textView.text substringWithRange:charRange];
521 lines.push_back(line.UTF8String);
522 // enumerateLineFragments overshoots maximumNumberOfLines by one on iOS
523 // 18, so cap explicitly.
524 if (maxLines > 0 && lines.size() >= (size_t)maxLines) {
525 *stop = YES;
526 }
527 }];
528​
529 if (_eventEmitter != nullptr) {
530 std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
531 ->onTextLayout(facebook::react::T3MarkdownTextEventEmitter::OnTextLayout{static_cast<int>(self.tag), lines});
532 };
534​
535- (void)loadAttachmentImages:(const std::vector<T3MarkdownTextAttachmentRange> &)attachmentRanges
537 for (const auto &attachmentRange : attachmentRanges) {
538 NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
539 if ([imageUri hasPrefix:@"sf:"]) {
540 continue;
541 }
542 NSDictionary *chip = T3ContextChipPayload(imageUri);
543 if (chip != nil) {
544 imageUri = [chip[@"iconUri"] isKindOfClass:NSString.class] ? chip[@"iconUri"] : nil;
545 if (imageUri.length == 0) continue;
546 }
547 if (_attachmentImages[imageUri] != nil || [_pendingAttachmentUris containsObject:imageUri]) {
548 continue;
549 }
550​
551 NSURL *url = [NSURL URLWithString:imageUri];
552 if (url == nil) {
553 continue;
554 }
555 if (url.isFileURL) {
556 UIImage *image = [UIImage imageWithContentsOfFile:url.path];
557 if (image != nil) {
558 _attachmentImages[imageUri] = image;
559 dispatch_async(dispatch_get_main_queue(), ^{
560 [self refreshDisplayedAttachments];
561 });
562 }
563 continue;
564 }
565​
566 [_pendingAttachmentUris addObject:imageUri];
567 [[[NSURLSession sharedSession] dataTaskWithURL:url
568 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
569 UIImage *image = data == nil ? nil : [UIImage imageWithData:data];
570 dispatch_async(dispatch_get_main_queue(), ^{
571 [self->_pendingAttachmentUris removeObject:imageUri];
572 if (image != nil) {
573 self->_attachmentImages[imageUri] = image;
574 [self refreshDisplayedAttachments];
575 }
576 });
577 }] resume];
578 }
580​
581- (void)refreshDisplayedAttachments
583 if (!_state || _textView.attributedText == nil) {
584 return;
585 }
586​
587 NSMutableAttributedString *attributedText = [_textView.attributedText mutableCopy];
588 T3MarkdownTextApplyAttachments(
589 attributedText,
590 _state->getData().attachmentRanges,
591 _attachmentImages);
592​
593 const NSRange savedRange = _textView.selectedRange;
594 _suppressSelectionChange = YES;
595 _textView.attributedText = attributedText;
596 if (savedRange.location != NSNotFound &&
597 NSMaxRange(savedRange) <= _textView.attributedText.length) {
598 _textView.selectedRange = savedRange;
599 }
600 _suppressSelectionChange = NO;
601 [_textView setNeedsDisplay];
603​
604- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
606 const auto &oldViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
607 const auto &newViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(props);
608 if (oldViewProps.contextClipboardConfig != newViewProps.contextClipboardConfig) {
609 NSString *config = RCTNSStringFromString(newViewProps.contextClipboardConfig);
610 _textView.contextClipboardConfig = config.length ? [NSJSONSerialization JSONObjectWithData:[config dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil] : nil;
611 }
612​
613 if (oldViewProps.numberOfLines != newViewProps.numberOfLines) {
614 _textView.textContainer.maximumNumberOfLines = newViewProps.numberOfLines;
615 }
616​
617 if (oldViewProps.selectable != newViewProps.selectable) {
618 _textView.selectable = newViewProps.selectable;
619 }
620​
621 if (oldViewProps.allowFontScaling != newViewProps.allowFontScaling) {
622 if (@available(iOS 11.0, *)) {
623 _textView.adjustsFontForContentSizeCategory = newViewProps.allowFontScaling;
624 }
625 }
626​
627 if (oldViewProps.ellipsizeMode != newViewProps.ellipsizeMode) {
628 if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
629 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingHead;
630 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
631 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingMiddle;
632 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
633 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingTail;
634 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Clip) {
635 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByClipping;
636 }
637 }
638​
639​
640 // I'm not sure if this is really the right way to handle this style. This means that the entire _view_ the text
641 // is in will have this background color applied. To apply it just to a particular part of a string, you'd need
642 // to do <Text><Text style={{backgroundColor: 'blue'}}>Hello</Text></Text>.
643 // This is how the base <Text> component works though, so we'll go with it for now. Can change later if we want.
644 if (oldViewProps.backgroundColor != newViewProps.backgroundColor) {
645 _textView.backgroundColor = RCTUIColorFromSharedColor(newViewProps.backgroundColor);
646 }
647​
648 [super updateProps:props oldProps:oldProps];
650​
651// See RCTParagraphComponentView
652- (void)updateState:(const facebook::react::State::Shared &)state oldState:(const facebook::react::State::Shared &)oldState
654 _state = std::static_pointer_cast<const T3MarkdownTextShadowNode::ConcreteState>(state);
655 [self setNeedsDisplay];
657​
658// MARK: - UIGestureRecognizerDelegate
659​
660- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
662 return YES;
664​
665- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
667 if (gestureRecognizer != _longPressGestureRecognizer &&
668 gestureRecognizer != _pressGestureRecognizer) {
669 return YES;
670 }
671​
672 const auto location = [self getLocationOfPress:gestureRecognizer];
673 const auto child = [self getTouchChild:location];
674 return ![child hasContextMenu];
676​
677- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
679 return YES;
681​
682- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView
684 if ([hitView isDescendantOfView:self]) {
685 return;
686 }
687 // Defer past the current event loop turn so any in-flight edit-menu action
688 // (Copy / Define / Look Up / …) reads the live selection before we clear it.
689 UITextView *textView = _textView;
690 dispatch_async(dispatch_get_main_queue(), ^{
691 UITextRange *range = textView.selectedTextRange;
692 if (range != nil && !range.isEmpty) {
693 textView.selectedTextRange = nil;
694 }
695 });
697​
698// MARK: - Touch handling
699​
700- (nullable T3MarkdownTextRun *)childForCharacterRange:(NSRange)characterRange
702 NSUInteger location = 0;
703 for (UIView *child in self.subviews) {
704 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
705 continue;
706 }
707​
708 T3MarkdownTextRun *textChild = (T3MarkdownTextRun *)child;
709 const NSRange range = NSMakeRange(location, textChild.text.length);
710 if (NSIntersectionRange(range, characterRange).length > 0) {
711 return textChild;
712 }
713 location = NSMaxRange(range);
714 }
715 return nil;
717​
718- (CGPoint)getLocationOfPress:(UIGestureRecognizer*)sender
720 return [sender locationInView:_textView];
722​
723- (T3MarkdownTextRun*)getTouchChild:(CGPoint)location
725 const auto charIndex = [_textView.layoutManager characterIndexForPoint:location
726 inTextContainer:_textView.textContainer
727 fractionOfDistanceBetweenInsertionPoints:nil
728 ];
729​
730 int currIndex = -1;
731 for (UIView* child in self.subviews) {
732 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
733 continue;
734 }
735​
736 T3MarkdownTextRun* textChild = (T3MarkdownTextRun*)child;
737​
738 // This is UTF16 code units!!
739 currIndex += textChild.text.length;
740​
741 if (charIndex <= currIndex) {
742 return textChild;
743 }
744 }
745​
746 return nil;
748​
749- (void)handlePressIfNecessary:(UITapGestureRecognizer*)sender
751 const auto location = [self getLocationOfPress:sender];
752 const auto child = [self getTouchChild:location];
753​
754 if (child) {
755 [child onPress];
756 }
758​
759- (void)handleLongPressIfNecessary:(UILongPressGestureRecognizer*)sender
761 if (sender.state != UIGestureRecognizerStateBegan) {
762 return;
763 }
764​
765 const auto location = [self getLocationOfPress:sender];
766 const auto child = [self getTouchChild:location];
767​
768 if (child) {
769 [child onLongPress];
770 }
772​
773// MARK: - UITextViewDelegate
774​
775- (nullable UIAction *)textView:(UITextView *)textView
776 primaryActionForTextItem:(UITextItem *)textItem
777 defaultAction:(UIAction *)defaultAction API_AVAILABLE(ios(17.0))
779 T3MarkdownTextRun *child = [self childForCharacterRange:textItem.range];
780 if (![child hasContextMenu] && !child.contextChipInteractive) {
781 return defaultAction;
782 }
783​
784 __weak T3MarkdownTextRun *weakChild = child;
785 return [UIAction actionWithHandler:^(__kindof UIAction *action) {
786 [weakChild onPress];
787 }];
789​
790- (nullable UITextItemMenuConfiguration *)textView:(UITextView *)textView
791 menuConfigurationForTextItem:(UITextItem *)textItem
792 defaultMenu:(UIMenu *)defaultMenu API_AVAILABLE(ios(17.0))
794 T3MarkdownTextRun *child = [self childForCharacterRange:textItem.range];
795 UIMenu *menu = [child contextMenu];
796 if (child.contextChipInteractive && menu == nil) return nil;
797 return [UITextItemMenuConfiguration configurationWithMenu:menu ?: defaultMenu];
799​
800- (void)textViewDidChangeSelection:(UITextView *)textView
802 if (_suppressSelectionChange) {
803 return;
804 }
805 if (_eventEmitter == nullptr) {
806 return;
807 }
808​
809 const NSRange selectedRange = textView.selectedRange;
810 if (selectedRange.location == NSNotFound) {
811 return;
812 }
813​
814 // Fires on programmatic selection changes too (e.g. the outside-tap clear
815 // in handleOutsideTap:), so JS will see a synthetic empty-range event then.
816 std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
817 ->onSelectionChange(facebook::react::T3MarkdownTextEventEmitter::OnSelectionChange{
818 static_cast<int>(self.tag),
819 static_cast<int>(selectedRange.location),
820 static_cast<int>(selectedRange.location + selectedRange.length),
821 });
823​
824Class<RCTComponentViewProtocol> T3MarkdownTextCls(void)
826 return T3MarkdownText.class;
828​
829@end