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

T3MarkdownText.mm

839 lines32.3 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;
290 BOOL _textLayoutNeedsUpdate;
292​
293+ (ComponentDescriptorProvider)componentDescriptorProvider
295 return concreteComponentDescriptorProvider<T3MarkdownTextComponentDescriptor>();
297​
298- (instancetype)initWithFrame:(CGRect)frame
300 if (self = [super initWithFrame:frame]) {
301 static const auto defaultProps = std::make_shared<const T3MarkdownTextProps>();
302 _props = defaultProps;
303​
304 _view = [[UIView alloc] init];
305 self.contentView = _view;
306 self.clipsToBounds = true;
307​
308 _textView = [[T3ContextCopyTextView alloc] init];
309 _attachmentImages = [[NSMutableDictionary alloc] init];
310 _pendingAttachmentUris = [[NSMutableSet alloc] init];
311 _textView.scrollEnabled = false;
312 _textView.editable = false;
313 _textView.textContainerInset = UIEdgeInsetsZero;
314 _textView.textContainer.lineFragmentPadding = 0;
315 // The shadow node already sized this view to fit every line. A container
316 // that tracks the frame can come out a fraction of a point shorter after
317 // pixel rounding, and TextKit then drops the last line. Size it by hand
318 // with unbounded height and let the view's bounds clip.
319 _textView.textContainer.widthTracksTextView = NO;
320 _textView.textContainer.heightTracksTextView = NO;
321 _textView.delegate = self;
322 // Chat text supports selection and contextual actions, but not drag-and-drop.
323 _textView.textDragInteraction.enabled = NO;
324 _textView.linkTextAttributes = @{};
325 // Must match RCTTextLayoutManager, which measures with usesFontLeading = NO.
326 _textView.layoutManager.usesFontLeading = NO;
327 [self addSubview:_textView];
328​
329 _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
330 action:@selector(handleLongPressIfNecessary:)];
331 _longPressGestureRecognizer.delegate = self;
332​
333 _pressGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
334 action:@selector(handlePressIfNecessary:)];
335 _pressGestureRecognizer.delegate = self;
336 [_pressGestureRecognizer requireGestureRecognizerToFail:_longPressGestureRecognizer];
337​
338 [_textView addGestureRecognizer:_pressGestureRecognizer];
339 [_textView addGestureRecognizer:_longPressGestureRecognizer];
340 }
341​
342 return self;
344​
345- (void)didMoveToWindow
347 [super didMoveToWindow];
348 if (_outsideTapWindow == self.window) {
349 return;
350 }
351 if (_outsideTapWindow != nil) {
352 T3MarkdownOutsideTapCoordinator *coordinator =
353 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
354 [coordinator removeTarget:self];
355 }
356 _outsideTapWindow = self.window;
357 if (_outsideTapWindow != nil) {
358 [T3MarkdownOutsideTapCoordinatorForWindow(_outsideTapWindow) addTarget:self];
359 }
361​
362- (void)dealloc
364 T3MarkdownOutsideTapCoordinator *coordinator =
365 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
366 [coordinator removeTarget:self];
368​
369- (NSArray *)accessibilityElements
371 return _contextAccessibilityElements ?: [super accessibilityElements];
373​
374// See RCTParagraphComponentView
375- (void)prepareForRecycle
377 [super prepareForRecycle];
378 T3MarkdownOutsideTapCoordinator *coordinator =
379 objc_getAssociatedObject(_outsideTapWindow, T3MarkdownOutsideTapCoordinatorKey);
380 [coordinator removeTarget:self];
381 _outsideTapWindow = nil;
382 _state.reset();
383​
384 // Reset the frame to zero so that when it properly lays out on the next use
385 _textView.frame = CGRectZero;
386 _textView.attributedText = nil;
387 _contextAccessibilityElements = nil;
388 _textLayoutNeedsUpdate = YES;
390​
391- (void)layoutSubviews
393 [super layoutSubviews];
394 // Resize during UIKit's layout pass. Doing this in drawRect can leave the
395 // text view's drawing surface clipped to its previous width after a pane
396 // expands, even though TextKit has already rewrapped the lines.
397 if (!CGRectEqualToRect(_textView.frame, _view.frame)) {
398 _textView.frame = _view.frame;
399 _textLayoutNeedsUpdate = YES;
400 [self setNeedsDisplay];
401 }
403​
404- (void)drawRect:(CGRect)rect
406 if (!_state) {
407 return;
408 }
409​
410 const auto &props = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
411​
412 const auto attrString = _state->getData().attributedString;
413 NSMutableAttributedString *convertedAttrString =
414 [RCTNSAttributedStringFromAttributedString(attrString) mutableCopy];
415 T3MarkdownTextApplyParagraphStyles(
416 convertedAttrString,
417 _state->getData().paragraphStyleRanges);
418 T3MarkdownTextApplyAttachments(
419 convertedAttrString,
420 _state->getData().attachmentRanges,
421 _attachmentImages);
422 // Matches the shadow node so drawn lines sit where measurement put them.
423 RCTApplyBaselineOffset(convertedAttrString);
424 NSUInteger runLocation = 0;
425 for (UIView *child in self.subviews) {
426 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
427 continue;
428 }
429​
430 T3MarkdownTextRun *textChild = (T3MarkdownTextRun *)child;
431 const NSRange runRange = NSMakeRange(runLocation, textChild.text.length);
432 runLocation = NSMaxRange(runRange);
433 if (![textChild hasContextMenu] || runRange.length == 0 ||
434 NSMaxRange(runRange) > convertedAttrString.length) {
435 continue;
436 }
437​
438 NSURL *link = [NSURL URLWithString:
439 [NSString stringWithFormat:@"t3-markdown-run://%ld", (long)textChild.tag]];
440 if (link != nil) {
441 // A glyph must not be both a link and an attachment. UIKit caches them as
442 // different text-item classes and can send `attachment` to a cached link
443 // on a later tap. Attachment actions already use primaryActionForTextItem.
444 [convertedAttrString enumerateAttribute:NSAttachmentAttributeName
445 inRange:runRange
446 options:0
447 usingBlock:^(id attachment, NSRange range, BOOL *stop) {
448 if (attachment == nil) {
449 [convertedAttrString addAttribute:NSLinkAttributeName value:link range:range];
450 }
451 }];
452 }
453 }
454 [self loadAttachmentImages:_state->getData().attachmentRanges];
455​
456 // Setting attributedText clears any active text selection, and re-assigning
457 // the frame triggers a layout flush that has the same effect. Bail out
458 // entirely when nothing actually changed so a JS-side state update made in
459 // response to onSelectionChange doesn't deselect what the user is selecting.
460 const BOOL textChanged = ![_textView.attributedText isEqualToAttributedString:convertedAttrString];
461 const BOOL frameChanged = _textLayoutNeedsUpdate;
462 if (!textChanged && !frameChanged) {
463 return;
464 }
465 if (textChanged) {
466 // Reassigning attributedText clears any active selection. Save it and
467 // restore after, while suppressing the synthetic textViewDidChangeSelection
468 // events the clear-then-restore would otherwise produce — those would
469 // round-trip to JS and re-trigger this same path, causing a loop.
470 const NSRange savedRange = _textView.selectedRange;
471 _suppressSelectionChange = YES;
472 _textView.attributedText = convertedAttrString;
473 NSMutableString *accessibleText = [convertedAttrString.string mutableCopy];
474 for (auto it = _state->getData().attachmentRanges.rbegin();
475 it != _state->getData().attachmentRanges.rend(); ++it) {
476 NSDictionary *chip = T3ContextChipPayload([NSString stringWithUTF8String:it->imageUri.c_str()]);
477 if (chip != nil && it->location < accessibleText.length) {
478 [accessibleText replaceCharactersInRange:NSMakeRange(it->location, 1) withString:chip[@"label"]];
479 }
480 }
481 _textView.accessibilityLabel = accessibleText;
482 if (savedRange.length > 0 && NSMaxRange(savedRange) <= _textView.attributedText.length) {
483 _textView.selectedRange = savedRange;
484 }
485 _suppressSelectionChange = NO;
486 }
487 if (frameChanged) {
488 _textView.textContainer.size = CGSizeMake(CGRectGetWidth(_view.frame), CGFLOAT_MAX);
489 }
490 _textLayoutNeedsUpdate = NO;
491​
492 // Text attachments have no native link element. Expose their existing runs
493 // at the measured glyph bounds, without inserting views into text layout.
494 NSMutableArray *accessibleElements = [NSMutableArray arrayWithObject:_textView];
495 for (UIView *child in self.subviews) {
496 if (![child isKindOfClass:T3MarkdownTextRun.class]) continue;
497 T3MarkdownTextRun *run = (T3MarkdownTextRun *)child;
498 run.contextChipInteractive = NO;
499 }
500 for (const auto &attachmentRange : _state->getData().attachmentRanges) {
501 NSDictionary *chip = T3ContextChipPayload(
502 [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()]);
503 if (![chip[@"interactive"] boolValue]) continue;
504 NSRange range = NSMakeRange(attachmentRange.location, 1);
505 T3MarkdownTextRun *run = [self childForCharacterRange:range];
506 if (!run || NSMaxRange(range) > convertedAttrString.length) continue;
507 NSRange glyphRange = [_textView.layoutManager glyphRangeForCharacterRange:range actualCharacterRange:nil];
508 CGRect bounds = [_textView.layoutManager boundingRectForGlyphRange:glyphRange
509 inTextContainer:_textView.textContainer];
510 bounds = CGRectOffset(bounds, _textView.textContainerInset.left, _textView.textContainerInset.top);
511 run.contextChipInteractive = YES;
512 T3ContextChipAccessibilityElement *element =
513 [[T3ContextChipAccessibilityElement alloc] initWithAccessibilityContainer:self];
514 element.run = run;
515 element.accessibilityLabel = chip[@"label"];
516 element.accessibilityTraits = UIAccessibilityTraitButton;
517 element.accessibilityFrameInContainerSpace = [_textView convertRect:bounds toView:self];
518 [accessibleElements addObject:element];
519 }
520 _contextAccessibilityElements = accessibleElements;
521​
522 __block std::vector<std::string> lines;
523 const int maxLines = props.numberOfLines;
524 [_textView.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, convertedAttrString.string.length) usingBlock:^(CGRect rect,
525 CGRect usedRect,
526 NSTextContainer * _Nonnull textContainer,
527 NSRange glyphRange,
528 BOOL * _Nonnull stop) {
529 const auto charRange = [self->_textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
530 const auto line = [self->_textView.text substringWithRange:charRange];
531 lines.push_back(line.UTF8String);
532 // enumerateLineFragments overshoots maximumNumberOfLines by one on iOS
533 // 18, so cap explicitly.
534 if (maxLines > 0 && lines.size() >= (size_t)maxLines) {
535 *stop = YES;
536 }
537 }];
538​
539 if (_eventEmitter != nullptr) {
540 std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
541 ->onTextLayout(facebook::react::T3MarkdownTextEventEmitter::OnTextLayout{static_cast<int>(self.tag), lines});
542 };
544​
545- (void)loadAttachmentImages:(const std::vector<T3MarkdownTextAttachmentRange> &)attachmentRanges
547 for (const auto &attachmentRange : attachmentRanges) {
548 NSString *imageUri = [NSString stringWithUTF8String:attachmentRange.imageUri.c_str()];
549 if ([imageUri hasPrefix:@"sf:"]) {
550 continue;
551 }
552 NSDictionary *chip = T3ContextChipPayload(imageUri);
553 if (chip != nil) {
554 imageUri = [chip[@"iconUri"] isKindOfClass:NSString.class] ? chip[@"iconUri"] : nil;
555 if (imageUri.length == 0) continue;
556 }
557 if (_attachmentImages[imageUri] != nil || [_pendingAttachmentUris containsObject:imageUri]) {
558 continue;
559 }
560​
561 NSURL *url = [NSURL URLWithString:imageUri];
562 if (url == nil) {
563 continue;
564 }
565 if (url.isFileURL) {
566 UIImage *image = [UIImage imageWithContentsOfFile:url.path];
567 if (image != nil) {
568 _attachmentImages[imageUri] = image;
569 dispatch_async(dispatch_get_main_queue(), ^{
570 [self refreshDisplayedAttachments];
571 });
572 }
573 continue;
574 }
575​
576 [_pendingAttachmentUris addObject:imageUri];
577 [[[NSURLSession sharedSession] dataTaskWithURL:url
578 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
579 UIImage *image = data == nil ? nil : [UIImage imageWithData:data];
580 dispatch_async(dispatch_get_main_queue(), ^{
581 [self->_pendingAttachmentUris removeObject:imageUri];
582 if (image != nil) {
583 self->_attachmentImages[imageUri] = image;
584 [self refreshDisplayedAttachments];
585 }
586 });
587 }] resume];
588 }
590​
591- (void)refreshDisplayedAttachments
593 if (!_state || _textView.attributedText == nil) {
594 return;
595 }
596​
597 NSMutableAttributedString *attributedText = [_textView.attributedText mutableCopy];
598 T3MarkdownTextApplyAttachments(
599 attributedText,
600 _state->getData().attachmentRanges,
601 _attachmentImages);
602​
603 const NSRange savedRange = _textView.selectedRange;
604 _suppressSelectionChange = YES;
605 _textView.attributedText = attributedText;
606 if (savedRange.location != NSNotFound &&
607 NSMaxRange(savedRange) <= _textView.attributedText.length) {
608 _textView.selectedRange = savedRange;
609 }
610 _suppressSelectionChange = NO;
611 [_textView setNeedsDisplay];
613​
614- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
616 const auto &oldViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(_props);
617 const auto &newViewProps = *std::static_pointer_cast<T3MarkdownTextProps const>(props);
618 if (oldViewProps.contextClipboardConfig != newViewProps.contextClipboardConfig) {
619 NSString *config = RCTNSStringFromString(newViewProps.contextClipboardConfig);
620 _textView.contextClipboardConfig = config.length ? [NSJSONSerialization JSONObjectWithData:[config dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil] : nil;
621 }
622​
623 if (oldViewProps.numberOfLines != newViewProps.numberOfLines) {
624 _textView.textContainer.maximumNumberOfLines = newViewProps.numberOfLines;
625 }
626​
627 if (oldViewProps.selectable != newViewProps.selectable) {
628 _textView.selectable = newViewProps.selectable;
629 }
630​
631 if (oldViewProps.allowFontScaling != newViewProps.allowFontScaling) {
632 if (@available(iOS 11.0, *)) {
633 _textView.adjustsFontForContentSizeCategory = newViewProps.allowFontScaling;
634 }
635 }
636​
637 if (oldViewProps.ellipsizeMode != newViewProps.ellipsizeMode) {
638 if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Head) {
639 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingHead;
640 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Middle) {
641 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingMiddle;
642 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Tail) {
643 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByTruncatingTail;
644 } else if (newViewProps.ellipsizeMode == T3MarkdownTextEllipsizeMode::Clip) {
645 _textView.textContainer.lineBreakMode = NSLineBreakMode::NSLineBreakByClipping;
646 }
647 }
648​
649​
650 // I'm not sure if this is really the right way to handle this style. This means that the entire _view_ the text
651 // is in will have this background color applied. To apply it just to a particular part of a string, you'd need
652 // to do <Text><Text style={{backgroundColor: 'blue'}}>Hello</Text></Text>.
653 // This is how the base <Text> component works though, so we'll go with it for now. Can change later if we want.
654 if (oldViewProps.backgroundColor != newViewProps.backgroundColor) {
655 _textView.backgroundColor = RCTUIColorFromSharedColor(newViewProps.backgroundColor);
656 }
657​
658 [super updateProps:props oldProps:oldProps];
660​
661// See RCTParagraphComponentView
662- (void)updateState:(const facebook::react::State::Shared &)state oldState:(const facebook::react::State::Shared &)oldState
664 _state = std::static_pointer_cast<const T3MarkdownTextShadowNode::ConcreteState>(state);
665 [self setNeedsDisplay];
667​
668// MARK: - UIGestureRecognizerDelegate
669​
670- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
672 return YES;
674​
675- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
677 if (gestureRecognizer != _longPressGestureRecognizer &&
678 gestureRecognizer != _pressGestureRecognizer) {
679 return YES;
680 }
681​
682 const auto location = [self getLocationOfPress:gestureRecognizer];
683 const auto child = [self getTouchChild:location];
684 return ![child hasContextMenu];
686​
687- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
689 return YES;
691​
692- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView
694 if ([hitView isDescendantOfView:self]) {
695 return;
696 }
697 // Defer past the current event loop turn so any in-flight edit-menu action
698 // (Copy / Define / Look Up / …) reads the live selection before we clear it.
699 UITextView *textView = _textView;
700 dispatch_async(dispatch_get_main_queue(), ^{
701 UITextRange *range = textView.selectedTextRange;
702 if (range != nil && !range.isEmpty) {
703 textView.selectedTextRange = nil;
704 }
705 });
707​
708// MARK: - Touch handling
709​
710- (nullable T3MarkdownTextRun *)childForCharacterRange:(NSRange)characterRange
712 NSUInteger location = 0;
713 for (UIView *child in self.subviews) {
714 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
715 continue;
716 }
717​
718 T3MarkdownTextRun *textChild = (T3MarkdownTextRun *)child;
719 const NSRange range = NSMakeRange(location, textChild.text.length);
720 if (NSIntersectionRange(range, characterRange).length > 0) {
721 return textChild;
722 }
723 location = NSMaxRange(range);
724 }
725 return nil;
727​
728- (CGPoint)getLocationOfPress:(UIGestureRecognizer*)sender
730 return [sender locationInView:_textView];
732​
733- (T3MarkdownTextRun*)getTouchChild:(CGPoint)location
735 const auto charIndex = [_textView.layoutManager characterIndexForPoint:location
736 inTextContainer:_textView.textContainer
737 fractionOfDistanceBetweenInsertionPoints:nil
738 ];
739​
740 int currIndex = -1;
741 for (UIView* child in self.subviews) {
742 if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
743 continue;
744 }
745​
746 T3MarkdownTextRun* textChild = (T3MarkdownTextRun*)child;
747​
748 // This is UTF16 code units!!
749 currIndex += textChild.text.length;
750​
751 if (charIndex <= currIndex) {
752 return textChild;
753 }
754 }
755​
756 return nil;
758​
759- (void)handlePressIfNecessary:(UITapGestureRecognizer*)sender
761 const auto location = [self getLocationOfPress:sender];
762 const auto child = [self getTouchChild:location];
763​
764 if (child) {
765 [child onPress];
766 }
768​
769- (void)handleLongPressIfNecessary:(UILongPressGestureRecognizer*)sender
771 if (sender.state != UIGestureRecognizerStateBegan) {
772 return;
773 }
774​
775 const auto location = [self getLocationOfPress:sender];
776 const auto child = [self getTouchChild:location];
777​
778 if (child) {
779 [child onLongPress];
780 }
782​
783// MARK: - UITextViewDelegate
784​
785- (nullable UIAction *)textView:(UITextView *)textView
786 primaryActionForTextItem:(UITextItem *)textItem
787 defaultAction:(UIAction *)defaultAction API_AVAILABLE(ios(17.0))
789 T3MarkdownTextRun *child = [self childForCharacterRange:textItem.range];
790 if (![child hasContextMenu] && !child.contextChipInteractive) {
791 return defaultAction;
792 }
793​
794 __weak T3MarkdownTextRun *weakChild = child;
795 return [UIAction actionWithHandler:^(__kindof UIAction *action) {
796 [weakChild onPress];
797 }];
799​
800- (nullable UITextItemMenuConfiguration *)textView:(UITextView *)textView
801 menuConfigurationForTextItem:(UITextItem *)textItem
802 defaultMenu:(UIMenu *)defaultMenu API_AVAILABLE(ios(17.0))
804 T3MarkdownTextRun *child = [self childForCharacterRange:textItem.range];
805 UIMenu *menu = [child contextMenu];
806 if (child.contextChipInteractive && menu == nil) return nil;
807 return [UITextItemMenuConfiguration configurationWithMenu:menu ?: defaultMenu];
809​
810- (void)textViewDidChangeSelection:(UITextView *)textView
812 if (_suppressSelectionChange) {
813 return;
814 }
815 if (_eventEmitter == nullptr) {
816 return;
817 }
818​
819 const NSRange selectedRange = textView.selectedRange;
820 if (selectedRange.location == NSNotFound) {
821 return;
822 }
823​
824 // Fires on programmatic selection changes too (e.g. the outside-tap clear
825 // in handleOutsideTap:), so JS will see a synthetic empty-range event then.
826 std::dynamic_pointer_cast<const facebook::react::T3MarkdownTextEventEmitter>(_eventEmitter)
827 ->onSelectionChange(facebook::react::T3MarkdownTextEventEmitter::OnSelectionChange{
828 static_cast<int>(self.tag),
829 static_cast<int>(selectedRange.location),
830 static_cast<int>(selectedRange.location + selectedRange.length),
831 });
833​
834Class<RCTComponentViewProtocol> T3MarkdownTextCls(void)
836 return T3MarkdownText.class;
838​
839@end