-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnrichedMarkdown.mm
More file actions
910 lines (780 loc) · 30.3 KB
/
EnrichedMarkdown.mm
File metadata and controls
910 lines (780 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
#import "EnrichedMarkdown.h"
#import "ContextMenuUtils.h"
#import "ENRMImageAttachment.h"
#import "ENRMMarkdownParser.h"
#import "ENRMTextRenderer.h"
#import "ENRMUIKit.h"
#import "EditMenuUtils.h"
#import "ENRMFeatureFlags.h"
#import "ENRMUIKit.h"
#if ENRICHED_MARKDOWN_MATH
#import "ENRMMathContainerView.h"
#endif
#import "ENRMSpoilerCapable.h"
#import "ENRMSpoilerOverlayView.h"
#import "ENRMSpoilerTapUtils.h"
#import "EnrichedMarkdownInternalText.h"
#import "FontScaleObserver.h"
#import "FontUtils.h"
#import "HeightUpdateUtils.h"
#import "LastElementUtils.h"
#import "LinkTapUtils.h"
#import "MarkdownASTNode.h"
#import "MarkdownAccessibilityElementBuilder.h"
#import "MarkdownExtractor.h"
#import "ParagraphStyleUtils.h"
#import "RuntimeKeys.h"
#import "StyleConfig.h"
#import "StylePropsUtils.h"
#import "TableContainerView.h"
#import "TaskListTapUtils.h"
#import "TextViewLayoutManager.h"
#import <React/RCTUtils.h>
#import <objc/runtime.h>
#import <ReactNativeEnrichedMarkdown/EnrichedMarkdownComponentDescriptor.h>
#import <ReactNativeEnrichedMarkdown/EventEmitters.h>
#import <ReactNativeEnrichedMarkdown/Props.h>
#import <ReactNativeEnrichedMarkdown/RCTComponentViewHelpers.h>
#import "RCTFabricComponentsPlugins.h"
#import <React/RCTConversions.h>
#import <React/RCTFont.h>
#import <react/utils/ManagedObjectWrapper.h>
using namespace facebook::react;
@interface EMTextSegment : NSObject
@property (nonatomic, strong) NSArray<MarkdownASTNode *> *nodes;
+ (instancetype)segmentWithNodes:(NSArray<MarkdownASTNode *> *)nodes;
@end
@implementation EMTextSegment
+ (instancetype)segmentWithNodes:(NSArray<MarkdownASTNode *> *)nodes
{
EMTextSegment *segment = [[EMTextSegment alloc] init];
segment.nodes = [nodes copy];
return segment;
}
@end
@interface EMTableSegment : NSObject
@property (nonatomic, strong) MarkdownASTNode *tableNode;
+ (instancetype)segmentWithTableNode:(MarkdownASTNode *)node;
@end
@implementation EMTableSegment
+ (instancetype)segmentWithTableNode:(MarkdownASTNode *)node
{
EMTableSegment *segment = [[EMTableSegment alloc] init];
segment.tableNode = node;
return segment;
}
@end
#if ENRICHED_MARKDOWN_MATH
@interface EMMathSegment : NSObject
@property (nonatomic, strong) NSString *latex;
+ (instancetype)segmentWithLatex:(NSString *)latex;
@end
@implementation EMMathSegment
+ (instancetype)segmentWithLatex:(NSString *)latex
{
EMMathSegment *segment = [[EMMathSegment alloc] init];
segment.latex = latex;
return segment;
}
@end
#endif
@interface EnrichedMarkdown () <RCTEnrichedMarkdownViewProtocol, UITextViewDelegate>
- (void)applySelectionColor:(const EnrichedMarkdownProps &)props toTextView:(ENRMPlatformTextView *)textView;
@end
@implementation EnrichedMarkdown {
ENRMMarkdownParser *_parser;
StyleConfig *_config;
ENRMMd4cFlags *_md4cFlags;
NSString *_cachedMarkdown;
NSString *_renderedMarkdown;
NSMutableArray<RCTUIView *> *_segmentViews;
dispatch_queue_t _renderQueue;
NSUInteger _currentRenderId;
BOOL _blockAsyncRender;
EnrichedMarkdownShadowNode::ConcreteState::Shared _state;
int _heightUpdateCounter;
FontScaleObserver *_fontScaleObserver;
CGFloat _maxFontSizeMultiplier;
BOOL _allowTrailingMargin;
BOOL _selectable;
BOOL _enableLinkPreview;
NSArray<NSString *> *_contextMenuItemTexts;
NSArray<NSString *> *_contextMenuItemIcons;
ENRMSpoilerOverlay _spoilerOverlay;
}
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<EnrichedMarkdownComponentDescriptor>();
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
static const auto defaultProps = std::make_shared<const EnrichedMarkdownProps>();
_props = defaultProps;
self.backgroundColor = [RCTUIColor clearColor];
_parser = [[ENRMMarkdownParser alloc] init];
_md4cFlags = [ENRMMd4cFlags defaultFlags];
_segmentViews = [NSMutableArray array];
_renderQueue = dispatch_queue_create("com.swmansion.enriched.markdown.container.render", DISPATCH_QUEUE_SERIAL);
_currentRenderId = 0;
_maxFontSizeMultiplier = 0;
_allowTrailingMargin = NO;
_selectable = YES;
_enableLinkPreview = YES;
_fontScaleObserver = [[FontScaleObserver alloc] init];
__weak EnrichedMarkdown *weakSelf = self;
_fontScaleObserver.onChange = ^{
EnrichedMarkdown *strongSelf = weakSelf;
if (!strongSelf)
return;
if (strongSelf->_config != nil) {
[strongSelf->_config setFontScaleMultiplier:strongSelf->_fontScaleObserver.effectiveFontScale];
}
if (strongSelf->_cachedMarkdown != nil && strongSelf->_cachedMarkdown.length > 0) {
[strongSelf renderMarkdownContent:strongSelf->_cachedMarkdown];
}
};
}
return self;
}
- (CGSize)computeSegmentLayoutForWidth:(CGFloat)width applyFrames:(BOOL)applyFrames
{
if (_segmentViews.count == 0)
return CGSizeZero;
__block CGFloat yOffset = 0.0;
__block CGFloat maxContentWidth = 0.0;
const NSUInteger lastIndex = _segmentViews.count - 1;
[_segmentViews enumerateObjectsUsingBlock:^(RCTUIView *segment, NSUInteger i, BOOL *stop) {
const BOOL isLast = (i == lastIndex);
const BOOL shouldAddBottomMargin = (!isLast || _allowTrailingMargin);
CGFloat segmentHeight = 0;
if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) {
EnrichedMarkdownInternalText *textView = (EnrichedMarkdownInternalText *)segment;
textView.allowTrailingMargin = shouldAddBottomMargin;
CGSize textSize = [textView measureSize:width];
segmentHeight = textSize.height;
maxContentWidth = MAX(maxContentWidth, textSize.width);
} else if ([segment isKindOfClass:[TableContainerView class]]) {
yOffset += _config.tableMarginTop;
segmentHeight = [(TableContainerView *)segment measureHeight:width];
maxContentWidth = width;
}
#if ENRICHED_MARKDOWN_MATH
else if ([segment isKindOfClass:[ENRMMathContainerView class]]) {
yOffset += _config.mathMarginTop;
segmentHeight = [(ENRMMathContainerView *)segment measureHeight:width];
maxContentWidth = width;
}
#endif
if (applyFrames) {
CGRect segmentFrame = CGRectMake(0, yOffset, width, segmentHeight);
segment.frame = segmentFrame;
#if TARGET_OS_OSX
if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) {
EnrichedMarkdownInternalText *textSeg = (EnrichedMarkdownInternalText *)segment;
textSeg.textView.frame = segment.bounds;
textSeg.textView.textContainer.size = CGSizeMake(width, CGFLOAT_MAX);
[textSeg.textView.layoutManager ensureLayoutForTextContainer:textSeg.textView.textContainer];
ENRMSetNeedsDisplay(textSeg.textView);
}
#endif
}
yOffset += segmentHeight;
if ([segment isKindOfClass:[TableContainerView class]] && shouldAddBottomMargin) {
yOffset += _config.tableMarginBottom;
}
#if ENRICHED_MARKDOWN_MATH
else if ([segment isKindOfClass:[ENRMMathContainerView class]] && shouldAddBottomMargin) {
yOffset += _config.mathMarginBottom;
}
#endif
}];
return CGSizeMake(maxContentWidth, yOffset);
}
- (CGSize)measureSize:(CGFloat)maxWidth
{
CGFloat defaultHeight = UIFontLineHeight([UIFont systemFontOfSize:16.0]);
CGSize contentSize = [self computeSegmentLayoutForWidth:maxWidth applyFrames:NO];
if (contentSize.height == 0)
return CGSizeMake(maxWidth, defaultHeight);
CGFloat scale = RCTScreenScale();
CGFloat measuredWidth = MIN(ceil(contentSize.width * scale) / scale, maxWidth);
CGFloat measuredHeight = ceil(contentSize.height * scale) / scale;
return CGSizeMake(measuredWidth, measuredHeight);
}
- (BOOL)hasRenderedMarkdown:(NSString *)markdown
{
return _renderedMarkdown != nil && [_renderedMarkdown isEqualToString:markdown];
}
- (void)updateState:(const facebook::react::State::Shared &)state
oldState:(const facebook::react::State::Shared &)oldState
{
_state = std::static_pointer_cast<const EnrichedMarkdownShadowNode::ConcreteState>(state);
if (oldState == nullptr) {
[self requestHeightUpdate];
}
}
- (void)requestHeightUpdate
{
if (_state == nullptr) {
return;
}
_heightUpdateCounter++;
auto selfRef = wrapManagedObjectWeakly(self);
_state->updateState(EnrichedMarkdownState(_heightUpdateCounter, selfRef));
}
- (NSArray *)splitASTIntoSegments:(MarkdownASTNode *)root
{
NSMutableArray *segments = [NSMutableArray array];
NSMutableArray *currentTextNodes = [NSMutableArray array];
for (MarkdownASTNode *child in root.children) {
if (child.type == MarkdownNodeTypeTable) {
if (currentTextNodes.count > 0) {
[segments addObject:[EMTextSegment segmentWithNodes:[currentTextNodes copy]]];
[currentTextNodes removeAllObjects];
}
[segments addObject:[EMTableSegment segmentWithTableNode:child]];
}
#if ENRICHED_MARKDOWN_MATH
else if (child.type == MarkdownNodeTypeLatexMathDisplay) {
#if !TARGET_OS_OSX
if (currentTextNodes.count > 0) {
[segments addObject:[EMTextSegment segmentWithNodes:[currentTextNodes copy]]];
[currentTextNodes removeAllObjects];
}
NSString *latex = child.children.count > 0 ? child.children.firstObject.content : child.content;
[segments addObject:[EMMathSegment segmentWithLatex:latex ?: @""]];
#else
// TODO: Fix block math rendering on macOS. Adding ENRMMathContainerView (which
// hosts MTMathUILabel) as a segment causes all preceding text segments to become
// invisible. Likely related to MTMathUILabel.layer.geometryFlipped interacting
// with NSTextView's coordinate system. Inline math ($...$) works.
#endif
}
#endif
else {
[currentTextNodes addObject:child];
}
}
if (currentTextNodes.count > 0) {
[segments addObject:[EMTextSegment segmentWithNodes:currentTextNodes]];
}
return segments;
}
- (void)renderMarkdownContent:(NSString *)markdownString
{
if (_blockAsyncRender) {
return;
}
_cachedMarkdown = [markdownString copy];
NSUInteger renderId = ++_currentRenderId;
StyleConfig *config = [_config copy];
ENRMMarkdownParser *parser = _parser;
ENRMMd4cFlags *md4cFlags = [_md4cFlags copy];
BOOL allowFontScaling = _fontScaleObserver.allowFontScaling;
CGFloat maxFontSizeMultiplier = _maxFontSizeMultiplier;
BOOL allowTrailingMargin = _allowTrailingMargin;
dispatch_async(_renderQueue, ^{
MarkdownASTNode *ast = [parser parseMarkdown:markdownString flags:md4cFlags];
if (!ast) {
return;
}
NSArray *segments = [self splitASTIntoSegments:ast];
NSMutableArray *renderedSegments = [NSMutableArray array];
for (id segment in segments) {
if ([segment isKindOfClass:[EMTextSegment class]]) {
ENRMRenderResult *rendered = [self renderTextSegment:(EMTextSegment *)segment
config:config
allowTrailingMargin:allowTrailingMargin
allowFontScaling:allowFontScaling
maxFontSizeMultiplier:maxFontSizeMultiplier];
[renderedSegments addObject:rendered];
} else if ([segment isKindOfClass:[EMTableSegment class]]) {
[renderedSegments addObject:segment];
}
#if ENRICHED_MARKDOWN_MATH
else if ([segment isKindOfClass:[EMMathSegment class]]) {
[renderedSegments addObject:segment];
}
#endif
}
dispatch_async(dispatch_get_main_queue(), ^{
if (renderId != self->_currentRenderId) {
return;
}
[self applyRenderedSegments:renderedSegments];
});
});
}
- (NSArray *)parseAndRenderSegments:(NSString *)markdownString
{
MarkdownASTNode *ast = [_parser parseMarkdown:markdownString flags:_md4cFlags];
if (!ast) {
return nil;
}
NSArray *segments = [self splitASTIntoSegments:ast];
NSMutableArray *renderedSegments = [NSMutableArray array];
for (id segment in segments) {
if ([segment isKindOfClass:[EMTextSegment class]]) {
ENRMRenderResult *rendered = [self renderTextSegment:(EMTextSegment *)segment
config:_config
allowTrailingMargin:_allowTrailingMargin
allowFontScaling:_fontScaleObserver.allowFontScaling
maxFontSizeMultiplier:_maxFontSizeMultiplier];
[renderedSegments addObject:rendered];
} else if ([segment isKindOfClass:[EMTableSegment class]]) {
[renderedSegments addObject:segment];
}
#if ENRICHED_MARKDOWN_MATH
else if ([segment isKindOfClass:[EMMathSegment class]]) {
[renderedSegments addObject:segment];
}
#endif
}
return renderedSegments;
}
/// Synchronous rendering for mock view measurement (no UI updates needed).
- (void)renderMarkdownSynchronously:(NSString *)markdownString
{
if (!markdownString || markdownString.length == 0) {
return;
}
for (RCTUIView *view in _segmentViews) {
[view removeFromSuperview];
}
[_segmentViews removeAllObjects];
_blockAsyncRender = YES;
_cachedMarkdown = [markdownString copy];
_renderedMarkdown = [markdownString copy];
NSArray *renderedSegments = [self parseAndRenderSegments:markdownString];
if (!renderedSegments) {
return;
}
for (id segment in renderedSegments) {
if ([segment isKindOfClass:[ENRMRenderResult class]]) {
EnrichedMarkdownInternalText *view = [self createTextViewForRenderedSegment:(ENRMRenderResult *)segment];
[_segmentViews addObject:view];
[self addSubview:view];
} else if ([segment isKindOfClass:[EMTableSegment class]]) {
TableContainerView *tableView = [self createTableViewForSegment:(EMTableSegment *)segment];
[_segmentViews addObject:tableView];
[self addSubview:tableView];
}
#if ENRICHED_MARKDOWN_MATH
else if ([segment isKindOfClass:[EMMathSegment class]]) {
ENRMMathContainerView *mathView = [self createMathViewForSegment:(EMMathSegment *)segment];
[_segmentViews addObject:mathView];
[self addSubview:mathView];
}
#endif
}
}
- (void)applyRenderedSegments:(NSArray *)renderedSegments
{
_renderedMarkdown = [_cachedMarkdown copy];
for (RCTUIView *view in _segmentViews) {
[view removeFromSuperview];
}
[_segmentViews removeAllObjects];
for (id segment in renderedSegments) {
if ([segment isKindOfClass:[ENRMRenderResult class]]) {
EnrichedMarkdownInternalText *view = [self createTextViewForRenderedSegment:(ENRMRenderResult *)segment];
[_segmentViews addObject:view];
[self addSubview:view];
} else if ([segment isKindOfClass:[EMTableSegment class]]) {
EMTableSegment *tableSegment = (EMTableSegment *)segment;
TableContainerView *tableView = [self createTableViewForSegment:tableSegment];
[_segmentViews addObject:tableView];
[self addSubview:tableView];
}
#if ENRICHED_MARKDOWN_MATH
else if ([segment isKindOfClass:[EMMathSegment class]]) {
EMMathSegment *mathSegment = (EMMathSegment *)segment;
ENRMMathContainerView *mathView = [self createMathViewForSegment:mathSegment];
[_segmentViews addObject:mathView];
[self addSubview:mathView];
}
#endif
}
if (self.bounds.size.width > 0) {
[self setNeedsLayout];
CGSize measured = [self measureSize:self.bounds.size.width];
if (needsHeightUpdate(measured, self.bounds)) {
[self requestHeightUpdate];
}
}
}
- (ENRMRenderResult *)renderTextSegment:(EMTextSegment *)textSegment
config:(StyleConfig *)config
allowTrailingMargin:(BOOL)allowTrailingMargin
allowFontScaling:(BOOL)allowFontScaling
maxFontSizeMultiplier:(CGFloat)maxFontSizeMultiplier
{
return ENRMRenderASTNodes(textSegment.nodes, config, allowTrailingMargin, allowFontScaling, maxFontSizeMultiplier,
currentWritingDirection());
}
- (EnrichedMarkdownInternalText *)createTextViewForRenderedSegment:(ENRMRenderResult *)segment
{
EnrichedMarkdownInternalText *view = [[EnrichedMarkdownInternalText alloc] initWithConfig:_config];
view.spoilerOverlay = _spoilerOverlay;
view.allowTrailingMargin = _allowTrailingMargin;
view.lastElementMarginBottom = segment.lastElementMarginBottom;
view.accessibilityInfo = segment.accessibilityInfo;
view.textView.selectable = _selectable;
[view applyAttributedText:segment.attributedText context:segment.context];
const auto &selectionProps = *std::static_pointer_cast<EnrichedMarkdownProps const>(self->_props);
[self applySelectionColor:selectionProps toTextView:view.textView];
ENRMTapRecognizer *tapRecognizer = [[ENRMTapRecognizer alloc] initWithTarget:self action:@selector(textTapped:)];
[view.textView addGestureRecognizer:tapRecognizer];
#if !TARGET_OS_OSX
view.textView.delegate = self;
#else
__weak EnrichedMarkdown *weakSelf = self;
[view setContextMenuProvider:^NSMenu *_Nullable(NSMenu *baseMenu, NSTextView *textView) {
EnrichedMarkdown *strongSelf = weakSelf;
if (!strongSelf) {
return baseMenu;
}
NSString *segmentMarkdown = extractMarkdownFromAttributedString(textView.textStorage, textView.selectedRange);
NSArray<NSMenuItem *> *customItems = ENRMBuildContextMenuItems(
strongSelf->_contextMenuItemTexts, strongSelf->_contextMenuItemIcons, textView,
^(NSString *itemText, NSString *selectedText, NSUInteger selectionStart, NSUInteger selectionEnd) {
auto eventEmitter = std::static_pointer_cast<EnrichedMarkdownEventEmitter const>(strongSelf->_eventEmitter);
if (eventEmitter) {
eventEmitter->onContextMenuItemPress({
.itemText = std::string(itemText.UTF8String),
.selectedText = std::string(selectedText.UTF8String),
.selectionStart = (int)selectionStart,
.selectionEnd = (int)selectionEnd,
});
}
});
return buildEditMenuForSelection(textView.textStorage, textView.selectedRange, segmentMarkdown, strongSelf->_config,
@[ baseMenu ], customItems);
}];
#endif
return view;
}
- (TableContainerView *)createTableViewForSegment:(EMTableSegment *)tableSegment
{
TableContainerView *tableView = [[TableContainerView alloc] initWithConfig:_config];
tableView.allowFontScaling = _fontScaleObserver.allowFontScaling;
tableView.maxFontSizeMultiplier = _maxFontSizeMultiplier;
tableView.enableLinkPreview = _enableLinkPreview;
__weak EnrichedMarkdown *weakSelf = self;
tableView.onLinkPress = ^(NSString *url) {
EnrichedMarkdown *strongSelf = weakSelf;
if (!strongSelf || !url)
return;
auto eventEmitter = std::static_pointer_cast<EnrichedMarkdownEventEmitter const>(strongSelf->_eventEmitter);
if (eventEmitter) {
eventEmitter->onLinkPress({.url = std::string([url UTF8String])});
}
};
tableView.onLinkLongPress = ^(NSString *url) {
EnrichedMarkdown *strongSelf = weakSelf;
if (!strongSelf || !url)
return;
auto eventEmitter = std::static_pointer_cast<EnrichedMarkdownEventEmitter const>(strongSelf->_eventEmitter);
if (eventEmitter) {
eventEmitter->onLinkLongPress({.url = std::string([url UTF8String])});
}
};
[tableView applyTableNode:tableSegment.tableNode];
return tableView;
}
#if ENRICHED_MARKDOWN_MATH
- (ENRMMathContainerView *)createMathViewForSegment:(EMMathSegment *)mathSegment
{
ENRMMathContainerView *mathView = [[ENRMMathContainerView alloc] initWithConfig:_config];
[mathView applyLatex:mathSegment.latex];
return mathView;
}
#endif
- (void)layoutSubviews
{
[super layoutSubviews];
[self computeSegmentLayoutForWidth:self.bounds.size.width applyFrames:YES];
}
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
{
const auto &oldViewProps = *std::static_pointer_cast<EnrichedMarkdownProps const>(_props);
const auto &newViewProps = *std::static_pointer_cast<EnrichedMarkdownProps const>(props);
BOOL stylePropChanged = NO;
if (_config == nil) {
_config = [[StyleConfig alloc] init];
[_config setFontScaleMultiplier:_fontScaleObserver.effectiveFontScale];
}
stylePropChanged = applyMarkdownStyleToConfig(_config, newViewProps.markdownStyle, oldViewProps.markdownStyle);
if (stylePropChanged) {
[ENRMImageAttachment clearAttachmentRegistry];
}
_selectable = newViewProps.selectable;
for (RCTUIView *segment in _segmentViews) {
if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) {
EnrichedMarkdownInternalText *textSegment = (EnrichedMarkdownInternalText *)segment;
if (textSegment.textView.selectable != newViewProps.selectable) {
textSegment.textView.selectable = newViewProps.selectable;
}
}
}
if (newViewProps.allowFontScaling != oldViewProps.allowFontScaling) {
_fontScaleObserver.allowFontScaling = newViewProps.allowFontScaling;
if (_config != nil) {
[_config setFontScaleMultiplier:_fontScaleObserver.effectiveFontScale];
}
stylePropChanged = YES;
}
if (newViewProps.maxFontSizeMultiplier != oldViewProps.maxFontSizeMultiplier) {
_maxFontSizeMultiplier = newViewProps.maxFontSizeMultiplier;
if (_config != nil) {
[_config setMaxFontSizeMultiplier:_maxFontSizeMultiplier];
}
stylePropChanged = YES;
}
if (newViewProps.allowTrailingMargin != oldViewProps.allowTrailingMargin) {
_allowTrailingMargin = newViewProps.allowTrailingMargin;
}
BOOL md4cFlagsChanged = NO;
if (newViewProps.md4cFlags.underline != oldViewProps.md4cFlags.underline) {
_md4cFlags.underline = newViewProps.md4cFlags.underline;
md4cFlagsChanged = YES;
}
if (newViewProps.md4cFlags.latexMath != oldViewProps.md4cFlags.latexMath) {
_md4cFlags.latexMath = newViewProps.md4cFlags.latexMath;
md4cFlagsChanged = YES;
}
BOOL markdownChanged = oldViewProps.markdown != newViewProps.markdown;
BOOL allowTrailingMarginChanged = newViewProps.allowTrailingMargin != oldViewProps.allowTrailingMargin;
_enableLinkPreview = newViewProps.enableLinkPreview;
if (ENRMContextMenuItemsChanged(oldViewProps.contextMenuItems, newViewProps.contextMenuItems)) {
_contextMenuItemTexts = ENRMContextMenuTextsFromItems(newViewProps.contextMenuItems);
_contextMenuItemIcons = ENRMContextMenuIconsFromItems(newViewProps.contextMenuItems);
}
if (newViewProps.spoilerOverlay != oldViewProps.spoilerOverlay) {
NSString *modeStr = [[NSString alloc] initWithUTF8String:newViewProps.spoilerOverlay.c_str()];
_spoilerOverlay = ENRMSpoilerOverlayFromString(modeStr);
for (RCTUIView *segment in _segmentViews) {
if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) {
((EnrichedMarkdownInternalText *)segment).spoilerOverlay = _spoilerOverlay;
}
}
}
if (newViewProps.selectionColor != oldViewProps.selectionColor) {
#if !TARGET_OS_OSX
for (RCTUIView *segment in _segmentViews) {
if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) {
ENRMPlatformTextView *tv = ((EnrichedMarkdownInternalText *)segment).textView;
[self applySelectionColor:newViewProps toTextView:tv];
}
}
#endif
}
if (markdownChanged || stylePropChanged || md4cFlagsChanged || allowTrailingMarginChanged) {
NSString *markdownString = [[NSString alloc] initWithUTF8String:newViewProps.markdown.c_str()];
[self renderMarkdownContent:markdownString];
}
[super updateProps:props oldProps:oldProps];
}
- (void)didMoveToWindow
{
[super didMoveToWindow];
if (self.window && _renderedMarkdown != nil) {
for (RCTUIView *segment in _segmentViews) {
if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) {
EnrichedMarkdownInternalText *textSegment = (EnrichedMarkdownInternalText *)segment;
ENRMRefreshTextViewAfterWindowAttach(textSegment.textView, textSegment.bounds);
}
}
CGSize measured = [self measureSize:self.bounds.size.width];
if (needsHeightUpdate(measured, self.bounds)) {
[self requestHeightUpdate];
}
}
}
Class<RCTComponentViewProtocol> EnrichedMarkdownCls(void)
{
return EnrichedMarkdown.class;
}
- (facebook::react::SharedTouchEventEmitter)touchEventEmitterAtPoint:(CGPoint)point
{
for (RCTUIView *segment in _segmentViews) {
if (![segment isKindOfClass:[EnrichedMarkdownInternalText class]]) {
continue;
}
EnrichedMarkdownInternalText *textSegment = (EnrichedMarkdownInternalText *)segment;
CGPoint segmentPoint = [self convertPoint:point toView:textSegment.textView];
#if !TARGET_OS_OSX
BOOL isInsideView = [textSegment.textView pointInside:segmentPoint withEvent:nil];
#else
BOOL isInsideView = CGRectContainsPoint(textSegment.textView.bounds, segmentPoint);
#endif
if (isInsideView) {
if (isPointOnInteractiveElement(textSegment.textView, segmentPoint)) {
return nil;
}
break;
}
}
return [super touchEventEmitterAtPoint:point];
}
#if TARGET_OS_OSX
- (void)mouseDown:(NSEvent *)event
{
for (RCTUIView *segment in _segmentViews) {
if (![segment isKindOfClass:[EnrichedMarkdownInternalText class]]) {
continue;
}
ENRMPlatformTextView *tv = ((EnrichedMarkdownInternalText *)segment).textView;
if (tv.selectedRange.length > 0) {
tv.selectedRange = NSMakeRange(0, 0);
}
}
[super mouseDown:event];
}
#endif
- (void)textTapped:(ENRMTapRecognizer *)recognizer
{
ENRMPlatformTextView *textView = (ENRMPlatformTextView *)recognizer.view;
if (handleTaskListTapWithSharedLogic(
textView, recognizer, &self->_cachedMarkdown, self->_config,
^(NSInteger index, BOOL checked, NSString *itemText) {
auto eventEmitter = std::static_pointer_cast<EnrichedMarkdownEventEmitter const>(self->_eventEmitter);
if (eventEmitter) {
eventEmitter->onTaskListItemPress({
.index = (int)index,
.checked = checked,
.text = std::string([itemText UTF8String] ?: ""),
});
}
},
^(NSString *updatedMarkdown) { [self renderMarkdownContent:updatedMarkdown]; })) {
return;
}
for (RCTUIView *segment in _segmentViews) {
if ([segment conformsToProtocol:@protocol(ENRMSpoilerCapable)]) {
id<ENRMSpoilerCapable> spoilerSegment = (id<ENRMSpoilerCapable>)segment;
if (spoilerSegment.textView == textView) {
if (handleSpoilerTap(textView, recognizer, spoilerSegment.spoilerManager))
return;
break;
}
}
}
NSString *url = linkURLAtTapLocation(textView, recognizer);
if (url) {
auto eventEmitter = std::static_pointer_cast<EnrichedMarkdownEventEmitter const>(_eventEmitter);
if (eventEmitter) {
eventEmitter->onLinkPress({.url = std::string([url UTF8String])});
}
return;
}
ENRMClearSelection(textView);
}
// TODO: Remove API_AVAILABLE(ios(16.0)) guard when the minimum iOS deployment target in RN is bumped to 16.
#if !TARGET_OS_OSX
- (UIMenu *)textView:(UITextView *)textView
editMenuForTextInRange:(NSRange)range
suggestedActions:(NSArray<UIMenuElement *> *)suggestedActions API_AVAILABLE(ios(16.0))
{
__weak EnrichedMarkdown *weakSelf = self;
ENRMContextMenuPressHandler handler =
^(NSString *itemText, NSString *selectedText, NSUInteger selectionStart, NSUInteger selectionEnd) {
EnrichedMarkdown *strongSelf = weakSelf;
if (!strongSelf)
return;
auto eventEmitter = std::static_pointer_cast<EnrichedMarkdownEventEmitter const>(strongSelf->_eventEmitter);
if (eventEmitter) {
eventEmitter->onContextMenuItemPress({
.itemText = std::string(itemText.UTF8String),
.selectedText = std::string(selectedText.UTF8String),
.selectionStart = (int)selectionStart,
.selectionEnd = (int)selectionEnd,
});
}
};
NSMutableArray<UIAction *> *customActions =
ENRMBuildContextMenuActions(_contextMenuItemTexts, _contextMenuItemIcons, textView, range, handler);
NSString *segmentMarkdown = extractMarkdownFromAttributedString(textView.attributedText, range);
return buildEditMenuForSelection(textView.attributedText, range, segmentMarkdown, _config, suggestedActions,
customActions);
}
- (BOOL)textView:(UITextView *)textView
shouldInteractWithURL:(NSURL *)URL
inRange:(NSRange)characterRange
interaction:(UITextItemInteraction)interaction
{
if (interaction != UITextItemInteractionPresentActions) {
return YES;
}
NSString *urlString = linkURLAtRange(textView, characterRange);
if (!urlString || _enableLinkPreview) {
return YES;
}
auto eventEmitter = std::static_pointer_cast<EnrichedMarkdownEventEmitter const>(_eventEmitter);
if (eventEmitter) {
eventEmitter->onLinkLongPress({.url = std::string([urlString UTF8String])});
}
return NO;
}
#endif
- (BOOL)isAccessibilityElement
{
return NO;
}
- (NSArray *)accessibilityElements
{
NSMutableArray *allElements = [NSMutableArray array];
for (RCTUIView *segment in _segmentViews) {
if ([segment isKindOfClass:[EnrichedMarkdownInternalText class]]) {
NSArray *elements = [(EnrichedMarkdownInternalText *)segment accessibilityElements];
if (elements) {
[allElements addObjectsFromArray:elements];
}
} else if ([segment isKindOfClass:[TableContainerView class]]) {
NSArray *elements = [(TableContainerView *)segment accessibilityElements];
if (elements) {
[allElements addObjectsFromArray:elements];
}
}
#if ENRICHED_MARKDOWN_MATH
else if ([segment isKindOfClass:[ENRMMathContainerView class]]) {
[allElements addObject:segment];
}
#endif
}
return allElements;
}
- (NSInteger)accessibilityElementCount
{
return [self accessibilityElements].count;
}
- (id)accessibilityElementAtIndex:(NSInteger)index
{
NSArray *elements = [self accessibilityElements];
if (index < 0 || index >= (NSInteger)elements.count) {
return nil;
}
return elements[index];
}
- (NSInteger)indexOfAccessibilityElement:(id)element
{
return [[self accessibilityElements] indexOfObject:element];
}
#if !TARGET_OS_OSX
- (NSArray<UIAccessibilityCustomRotor *> *)accessibilityCustomRotors
{
return [MarkdownAccessibilityElementBuilder buildRotorsFromElements:[self accessibilityElements]];
}
#endif
- (void)applySelectionColor:(const EnrichedMarkdownProps &)props toTextView:(ENRMPlatformTextView *)textView
{
#if !TARGET_OS_OSX
if (isColorMeaningful(props.selectionColor)) {
ENRMSetSelectionColor(textView, RCTUIColorFromSharedColor(props.selectionColor));
} else {
ENRMSetSelectionColor(textView, nil);
}
#endif
}
@end