-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathEnrichedMarkdownInput.mm
More file actions
1349 lines (1111 loc) · 39 KB
/
EnrichedMarkdownInput.mm
File metadata and controls
1349 lines (1111 loc) · 39 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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "EnrichedMarkdownInput.h"
#import "ContextMenuUtils.h"
#import "ENRMAutoLinkDetector.h"
#import "ENRMDetectorPipeline.h"
#import "ENRMFormattingRange.h"
#import "ENRMFormattingStore.h"
#import "ENRMInputFormatter.h"
#import "ENRMInputLayoutManager.h"
#import "ENRMInputLinkPrompt.h"
#import "ENRMInputParser.h"
#import "ENRMInputTextView.h"
#import "ENRMLinkRegexConfig.h"
#import "ENRMMarkdownSerializer.h"
#import "ENRMStyleHandler.h"
#import "ENRMStyleMergingConfig.h"
#import "ENRMUIKit.h"
#import "InputStylePropsUtils.h"
#if TARGET_OS_OSX
#import <React/RCTBackedTextInputDelegate.h>
#endif
#import <ReactNativeEnrichedMarkdown/EnrichedMarkdownInputComponentDescriptor.h>
#import <ReactNativeEnrichedMarkdown/EventEmitters.h>
#import <ReactNativeEnrichedMarkdown/Props.h>
#import <ReactNativeEnrichedMarkdown/RCTComponentViewHelpers.h>
#import "EnrichedMarkdownInputShadowNode.h"
#import "RCTFabricComponentsPlugins.h"
#import <React/RCTConversions.h>
#import <react/utils/ManagedObjectWrapper.h>
using namespace facebook::react;
#if !TARGET_OS_OSX
@interface EnrichedMarkdownInput () <RCTEnrichedMarkdownInputViewProtocol, UITextViewDelegate>
#else
@interface EnrichedMarkdownInput () <RCTEnrichedMarkdownInputViewProtocol, RCTBackedTextInputDelegate>
#endif
- (void)setupTextView;
- (void)applyFormatting;
- (void)toggleInlineStyle:(ENRMInputStyleType)styleType;
- (void)resetBaseTypingAttributes;
- (void)replaceSelectedTextWith:(NSString *)text formattingRanges:(NSArray<ENRMFormattingRange *> *)ranges;
@end
@implementation EnrichedMarkdownInput {
ENRMPlatformTextView *_textView;
ENRMInputLayoutManager *_layoutManager;
EnrichedMarkdownInputShadowNode::ConcreteState::Shared _state;
int _heightUpdateCounter;
ENRMInputFormatter *_formatter;
ENRMInputFormatterStyle *_formatterStyle;
ENRMFormattingStore *_formattingStore;
NSMutableSet<NSNumber *> *_pendingStyles;
NSMutableSet<NSNumber *> *_pendingStyleRemovals;
BOOL _isApplyingFormatting;
BOOL _isTextChanging;
BOOL _emitMarkdown;
ENRMPlaceholderLabel *_placeholderLabel;
NSUInteger _lastTextLength;
NSRange _lastSelectedRange;
NSRange _preEditSelectedRange;
struct {
BOOL bold, italic, underline, strikethrough, spoiler, link, initialized;
} _prevState;
std::optional<CGRect> _prevCaretRect;
#if TARGET_OS_OSX
NSScrollView *_scrollView;
#endif
NSArray<NSString *> *_contextMenuItemTexts;
NSArray<NSString *> *_contextMenuItemIcons;
ENRMAutoLinkDetector *_autoLinkDetector;
ENRMDetectorPipeline *_detectorPipeline;
}
#pragma mark - Fabric lifecycle
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<EnrichedMarkdownInputComponentDescriptor>();
}
+ (BOOL)shouldBeRecycled
{
return NO;
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
static const auto defaultProps = std::make_shared<const EnrichedMarkdownInputProps>();
_props = defaultProps;
self.backgroundColor = [RCTUIColor clearColor];
_blockEmitting = NO;
_heightUpdateCounter = 0;
_formatter = [[ENRMInputFormatter alloc] init];
_formatterStyle = [[ENRMInputFormatterStyle alloc] init];
_formattingStore = [[ENRMFormattingStore alloc] init];
_pendingStyles = [NSMutableSet set];
_pendingStyleRemovals = [NSMutableSet set];
_lastTextLength = 0;
_lastSelectedRange = NSMakeRange(0, 0);
[self setupTextView];
[self setupDetectorPipeline];
}
return self;
}
- (void)setupDetectorPipeline
{
_autoLinkDetector = [[ENRMAutoLinkDetector alloc] initWithTextStorage:_textView.textStorage
formattingStore:_formattingStore
style:_formatterStyle];
__weak EnrichedMarkdownInput *weakSelf = self;
_autoLinkDetector.onLinkDetected = ^(NSString *text, NSString *url, NSRange range) {
[weakSelf emitOnLinkDetectedWithText:text url:url range:range];
};
_detectorPipeline = [[ENRMDetectorPipeline alloc] init];
[_detectorPipeline addDetector:_autoLinkDetector];
}
- (void)setupTextView
{
#if !TARGET_OS_OSX
_layoutManager = [[ENRMInputLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(0, CGFLOAT_MAX)];
textContainer.widthTracksTextView = YES;
[_layoutManager addTextContainer:textContainer];
NSTextStorage *textStorage = [[NSTextStorage alloc] init];
[textStorage addLayoutManager:_layoutManager];
ENRMInputTextView *inputTextView = [[ENRMInputTextView alloc] initWithFrame:CGRectZero textContainer:textContainer];
#else
ENRMInputTextView *inputTextView = [[ENRMInputTextView alloc] initWithFrame:CGRectZero];
#endif
inputTextView.markdownInput = self;
_textView = inputTextView;
ENRMConfigureMarkdownInputTextView(_textView);
#if !TARGET_OS_OSX
_textView.adjustsFontForContentSizeCategory = YES;
_textView.delegate = self;
#else
_textView.textInputDelegate = self;
#endif
#if !TARGET_OS_OSX
self.contentView = _textView;
#else
_textView.selectable = YES;
_scrollView = [[NSScrollView alloc] initWithFrame:CGRectZero];
_scrollView.backgroundColor = [RCTUIColor clearColor];
_scrollView.drawsBackground = NO;
_scrollView.borderType = NSNoBorder;
_scrollView.hasHorizontalRuler = NO;
_scrollView.hasVerticalRuler = NO;
_scrollView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
_textView.verticallyResizable = YES;
_textView.horizontallyResizable = YES;
_textView.textContainer.containerSize = NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX);
_textView.textContainer.widthTracksTextView = YES;
_scrollView.documentView = _textView;
self.contentView = _scrollView;
#endif
_placeholderLabel = ENRMCreatePlaceholderLabel(_textView, _formatterStyle.baseFont);
#if !TARGET_OS_OSX
_placeholderLabel.adjustsFontForContentSizeCategory = YES;
#endif
[self resetBaseTypingAttributes];
}
#pragma mark - State
- (void)updateState:(const facebook::react::State::Shared &)state
oldState:(const facebook::react::State::Shared &)oldState
{
_state = std::static_pointer_cast<const EnrichedMarkdownInputShadowNode::ConcreteState>(state);
if (oldState == nullptr) {
[self requestHeightUpdate];
}
}
- (void)requestHeightUpdate
{
if (_state == nullptr) {
return;
}
_heightUpdateCounter++;
auto selfRef = wrapManagedObjectWeakly(self);
_state->updateState(EnrichedMarkdownInputState(_heightUpdateCounter, selfRef));
}
#pragma mark - Measurement
- (CGSize)measureSize:(CGFloat)maxWidth
{
NSMutableAttributedString *measuredText =
[[NSMutableAttributedString alloc] initWithAttributedString:ENRMGetAttributedText(_textView)];
// Empty input should still be the height of a single line.
// Use typingAttributes so the measurement matches the actual configured font.
if (measuredText.length == 0) {
[measuredText appendAttributedString:[[NSAttributedString alloc] initWithString:@"I"
attributes:_textView.typingAttributes]];
}
// Trailing newlines are not counted by boundingRectWithSize — append
// a mock character so the extra line is included in the height.
if (measuredText.length > 0) {
unichar lastChar = [measuredText.string characterAtIndex:measuredText.length - 1];
if ([[NSCharacterSet newlineCharacterSet] characterIsMember:lastChar]) {
[measuredText appendAttributedString:[[NSAttributedString alloc] initWithString:@"I"
attributes:_textView.typingAttributes]];
}
}
CGRect boundingBox =
[measuredText boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
context:nil];
return CGSizeMake(maxWidth, ceil(boundingBox.size.height));
}
#pragma mark - Props
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
{
const auto &oldViewProps = *std::static_pointer_cast<EnrichedMarkdownInputProps const>(_props);
const auto &newViewProps = *std::static_pointer_cast<EnrichedMarkdownInputProps const>(props);
if (newViewProps.editable != oldViewProps.editable) {
_textView.editable = newViewProps.editable;
}
#if !TARGET_OS_OSX
if (newViewProps.scrollEnabled != oldViewProps.scrollEnabled) {
_textView.scrollEnabled = newViewProps.scrollEnabled;
}
if (newViewProps.autoCapitalize != oldViewProps.autoCapitalize) {
NSString *value = [NSString stringWithUTF8String:newViewProps.autoCapitalize.c_str()];
_textView.autocapitalizationType = ENRMAutocapitalizationTypeFromString(value);
if ([_textView isFirstResponder]) {
[_textView resignFirstResponder];
[_textView becomeFirstResponder];
}
}
if (newViewProps.multiline != oldViewProps.multiline) {
_textView.textContainer.maximumNumberOfLines = newViewProps.multiline ? 0 : 1;
_textView.textContainer.lineBreakMode =
newViewProps.multiline ? NSLineBreakByWordWrapping : NSLineBreakByTruncatingTail;
}
#endif
if (newViewProps.placeholder != oldViewProps.placeholder) {
ENRMSetPlaceholderText(_placeholderLabel, [NSString stringWithUTF8String:newViewProps.placeholder.c_str()]);
}
if (newViewProps.placeholderTextColor != oldViewProps.placeholderTextColor) {
if (isColorMeaningful(newViewProps.placeholderTextColor)) {
_placeholderLabel.textColor = RCTUIColorFromSharedColor(newViewProps.placeholderTextColor);
}
}
if (newViewProps.cursorColor != oldViewProps.cursorColor) {
if (isColorMeaningful(newViewProps.cursorColor)) {
ENRMSetCursorColor(_textView, RCTUIColorFromSharedColor(newViewProps.cursorColor));
}
}
if (newViewProps.selectionColor != oldViewProps.selectionColor) {
if (isColorMeaningful(newViewProps.selectionColor)) {
ENRMSetSelectionColor(_textView, RCTUIColorFromSharedColor(newViewProps.selectionColor));
}
}
_emitMarkdown = newViewProps.isOnChangeMarkdownSet;
{
auto configFromProp = [](const auto &prop) {
return [[ENRMLinkRegexConfig alloc] initWithPattern:[NSString stringWithUTF8String:prop.pattern.c_str()]
caseInsensitive:prop.caseInsensitive
dotAll:prop.dotAll
isDisabled:prop.isDisabled
isDefault:prop.isDefault];
};
ENRMLinkRegexConfig *oldRegexConfig = configFromProp(oldViewProps.linkRegex);
ENRMLinkRegexConfig *newRegexConfig = configFromProp(newViewProps.linkRegex);
if (![newRegexConfig isEqualToConfig:oldRegexConfig]) {
[_autoLinkDetector setRegexConfig:newRegexConfig];
}
}
if (ENRMContextMenuItemsChanged(oldViewProps.contextMenuItems, newViewProps.contextMenuItems)) {
_contextMenuItemTexts = ENRMContextMenuTextsFromItems(newViewProps.contextMenuItems);
_contextMenuItemIcons = ENRMContextMenuIconsFromItems(newViewProps.contextMenuItems);
}
BOOL styleChanged = applyInputStyleProps(_formatterStyle, newViewProps, oldViewProps);
if (newViewProps.defaultValue != oldViewProps.defaultValue) {
if (!newViewProps.defaultValue.empty() && oldViewProps.defaultValue.empty()) {
NSString *markdown = [NSString stringWithUTF8String:newViewProps.defaultValue.c_str()];
[self importMarkdown:markdown];
}
}
if (styleChanged) {
_placeholderLabel.font = _formatterStyle.baseFont;
[self resetBaseTypingAttributes];
if (_formattingStore.allRanges.count > 0) {
[self applyFormatting];
}
[self requestHeightUpdate];
}
[super updateProps:props oldProps:oldProps];
}
#pragma mark - Relayout
- (void)scheduleRelayoutIfNeeded
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_performRelayout) object:nil];
[self performSelector:@selector(_performRelayout) withObject:nil afterDelay:0];
}
- (void)_performRelayout
{
if (!_textView) {
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
NSUInteger textLength = self->_textView.textStorage.length;
if (textLength == 0) {
return;
}
NSRange wholeRange = NSMakeRange(0, textLength);
NSRange actualRange = NSMakeRange(0, 0);
[self->_textView.layoutManager invalidateLayoutForCharacterRange:wholeRange actualCharacterRange:&actualRange];
[self->_textView.layoutManager ensureLayoutForCharacterRange:actualRange];
[self->_textView.layoutManager invalidateDisplayForCharacterRange:wholeRange];
CGSize measuredSize = [self measureSize:self->_textView.frame.size.width];
ENRMSetContentSize(self->_textView, measuredSize);
});
}
#pragma mark - Window attachment
- (void)didMoveToWindow
{
[super didMoveToWindow];
if (self.window) {
// Don't override the contentView frame set by RCTViewComponentView.
ENRMRefreshTextViewLayout(_textView);
[self applyFormatting];
[self updatePlaceholderVisibility];
[self requestHeightUpdate];
const auto &viewProps = *std::static_pointer_cast<EnrichedMarkdownInputProps const>(_props);
if (viewProps.autoFocus) {
ENRMFocusTextView(_textView);
}
}
}
#if TARGET_OS_OSX
#pragma mark - macOS responder chain
- (BOOL)acceptsFirstResponder
{
return _textView.acceptsFirstResponder;
}
- (BOOL)becomeFirstResponder
{
return [self.window makeFirstResponder:_textView];
}
- (BOOL)needsPanelToBecomeKey
{
return YES;
}
- (BOOL)mouseDownCanMoveWindow
{
return NO;
}
- (void)mouseDown:(NSEvent *)event
{
[self.window makeFirstResponder:_textView];
[_textView mouseDown:event];
}
#endif
#if !TARGET_OS_OSX
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
{
[super traitCollectionDidChange:previousTraitCollection];
if (previousTraitCollection.preferredContentSizeCategory != self.traitCollection.preferredContentSizeCategory) {
[_formatterStyle invalidateFontCache];
[self resetBaseTypingAttributes];
_placeholderLabel.font = _formatterStyle.baseFont;
[self applyFormatting];
[self requestHeightUpdate];
}
}
#endif
#pragma mark - Placeholder
- (void)updatePlaceholderVisibility
{
_placeholderLabel.hidden = (ENRMGetPlainText(_textView).length > 0);
}
#pragma mark - Markdown import
- (void)importMarkdown:(NSString *)markdown
{
ENRMInputParser *parser = [[ENRMInputParser alloc] init];
ENRMParseResult *parsed = [parser parseToPlainTextAndRanges:markdown];
_blockEmitting = YES;
_isApplyingFormatting = YES;
ENRMSetPlainText(_textView, parsed.plainText);
_isApplyingFormatting = NO;
[_formattingStore setRanges:parsed.formattingRanges];
_lastTextLength = parsed.plainText.length;
_lastSelectedRange = _textView.selectedRange;
[self applyFormatting];
[self updatePlaceholderVisibility];
_blockEmitting = NO;
}
- (void)replaceSelectedTextWith:(NSString *)text formattingRanges:(NSArray<ENRMFormattingRange *> *)ranges
{
NSRange selection = _textView.selectedRange;
NSUInteger editLocation = selection.location;
_isApplyingFormatting = YES;
ENRMReplaceTextInRange(_textView, text, selection);
_isApplyingFormatting = NO;
[_formattingStore adjustForEditAtLocation:editLocation deletedLength:selection.length insertedLength:text.length];
for (ENRMFormattingRange *range in ranges) {
NSRange shifted = NSMakeRange(range.range.location + editLocation, range.range.length);
[_formattingStore addRange:[ENRMFormattingRange rangeWithType:range.type range:shifted url:range.url]];
}
_lastTextLength = ENRMGetPlainText(_textView).length;
_lastSelectedRange = _textView.selectedRange;
[self applyFormatting];
[_detectorPipeline processTextChange:ENRMGetPlainText(_textView)
modificationRange:NSMakeRange(editLocation, text.length)];
[self updatePlaceholderVisibility];
[self emitOnChangeText];
[self emitOnChangeSelection];
[self emitFormattingChanged];
[self requestHeightUpdate];
[self scheduleRelayoutIfNeeded];
}
- (void)pasteMarkdown:(NSString *)markdown
{
ENRMInputParser *parser = [[ENRMInputParser alloc] init];
ENRMParseResult *parsed = [parser parseToPlainTextAndRanges:markdown];
[self replaceSelectedTextWith:parsed.plainText formattingRanges:parsed.formattingRanges];
}
#pragma mark - Formatting
- (void)resetBaseTypingAttributes
{
ENRMSetDefaultTypingAttributes(_textView, @{
NSFontAttributeName : _formatterStyle.baseFont,
NSForegroundColorAttributeName : _formatterStyle.baseTextColor,
});
}
- (void)applyFormatting
{
if (_isApplyingFormatting) {
return;
}
if (ENRMHasMarkedText(_textView)) {
return;
}
_isApplyingFormatting = YES;
NSRange savedSelection = _textView.selectedRange;
[_formatter applyFormattingRanges:_formattingStore.allRanges toTextView:_textView style:_formatterStyle];
[_detectorPipeline refreshAllStyling];
NSUInteger textLen = ENRMGetPlainText(_textView).length;
if (savedSelection.location + savedSelection.length <= textLen) {
_textView.selectedRange = savedSelection;
}
_isApplyingFormatting = NO;
}
#pragma mark - Commands
- (void)focus
{
ENRMFocusTextView(_textView);
}
- (void)blur
{
ENRMBlurTextView(_textView);
}
- (void)setValue:(NSString *)markdown
{
[self importMarkdown:markdown];
_lastSelectedRange = _textView.selectedRange;
[self emitOnChangeText];
[self emitOnChangeSelection];
[self emitOnChangeState];
[self requestHeightUpdate];
}
- (void)setSelection:(NSInteger)start end:(NSInteger)end
{
NSInteger textLen = (NSInteger)ENRMGetPlainText(_textView).length;
NSInteger clampedStart = MIN(MAX(start, 0), textLen);
NSInteger clampedEnd = MIN(MAX(end, clampedStart), textLen);
_textView.selectedRange = NSMakeRange((NSUInteger)clampedStart, (NSUInteger)(clampedEnd - clampedStart));
[self emitOnChangeSelection];
[self emitOnChangeState];
}
- (void)toggleBold
{
[self toggleInlineStyle:ENRMInputStyleTypeStrong];
}
- (void)toggleItalic
{
[self toggleInlineStyle:ENRMInputStyleTypeEmphasis];
}
- (void)toggleUnderline
{
[self toggleInlineStyle:ENRMInputStyleTypeUnderline];
}
- (void)toggleStrikethrough
{
[self toggleInlineStyle:ENRMInputStyleTypeStrikethrough];
}
- (void)toggleSpoiler
{
[self toggleInlineStyle:ENRMInputStyleTypeSpoiler];
}
- (void)toggleInlineStyle:(ENRMInputStyleType)styleType
{
id<ENRMStyleHandler> handler = [_formatter handlerForStyleType:styleType];
if (!handler) {
return;
}
ENRMStyleMergingConfig *mergingConfig = handler.mergingConfig;
NSRange selection = _textView.selectedRange;
NSUInteger cursor = selection.location;
NSNumber *key = @(styleType);
// Check blocking rules: if any blocking style is active, refuse to toggle on.
if (mergingConfig.blockingStyles.count > 0) {
BOOL isCurrentlyActive = [_formattingStore isStyleActive:styleType atPosition:cursor];
if (!isCurrentlyActive) {
for (NSNumber *blockerNum in mergingConfig.blockingStyles) {
if ([_formattingStore isStyleActive:(ENRMInputStyleType)blockerNum.integerValue atPosition:cursor]) {
return;
}
}
}
}
if (selection.length > 0) {
BOOL fullyStyled = YES;
NSUInteger pos = selection.location;
NSUInteger selEnd = NSMaxRange(selection);
while (pos < selEnd) {
ENRMFormattingRange *match = [_formattingStore rangeOfType:styleType containingPosition:pos];
if (match == nil) {
fullyStyled = NO;
break;
}
pos = NSMaxRange(match.range);
}
if (fullyStyled) {
[_formattingStore removeType:styleType inRange:selection];
} else {
// Remove conflicting styles from the range before applying.
for (NSNumber *conflictNum in mergingConfig.conflictingStyles) {
[_formattingStore removeType:(ENRMInputStyleType)conflictNum.integerValue inRange:selection];
}
ENRMFormattingRange *newRange = [ENRMFormattingRange rangeWithType:styleType range:selection];
[_formattingStore addRange:newRange];
}
[_pendingStyles removeObject:key];
[_pendingStyleRemovals removeObject:key];
} else {
BOOL isInsideRange = [_formattingStore isStyleActive:styleType atPosition:cursor];
if ([_pendingStyleRemovals containsObject:key]) {
[_pendingStyleRemovals removeObject:key];
} else if ([_pendingStyles containsObject:key]) {
[_pendingStyles removeObject:key];
} else if (isInsideRange) {
[_pendingStyleRemovals addObject:key];
} else {
[_pendingStyles addObject:key];
}
}
[self applyFormatting];
[self emitFormattingChanged];
}
- (void)setLink:(NSString *)url
{
NSRange selection = _textView.selectedRange;
NSUInteger cursor = selection.location;
ENRMFormattingRange *activeLink = [_formattingStore rangeOfType:ENRMInputStyleTypeLink containingPosition:cursor];
if (activeLink != nil) {
activeLink.url = url;
[_autoLinkDetector clearAutoLinkInRange:activeLink.range];
} else if (selection.length > 0) {
ENRMFormattingRange *linkRange = [ENRMFormattingRange rangeWithType:ENRMInputStyleTypeLink range:selection url:url];
[_formattingStore addRange:linkRange];
[_autoLinkDetector clearAutoLinkInRange:selection];
} else {
return;
}
[self applyFormatting];
[self emitFormattingChanged];
}
- (void)insertLink:(NSString *)text url:(NSString *)url
{
NSString *displayText = text.length > 0 ? text : url;
NSRange linkRange = NSMakeRange(0, displayText.length);
ENRMFormattingRange *range = [ENRMFormattingRange rangeWithType:ENRMInputStyleTypeLink range:linkRange url:url];
[self replaceSelectedTextWith:displayText formattingRanges:@[ range ]];
}
- (void)removeLink
{
NSUInteger cursor = _textView.selectedRange.location;
ENRMFormattingRange *activeLink = [_formattingStore rangeOfType:ENRMInputStyleTypeLink containingPosition:cursor];
if (activeLink == nil) {
return;
}
[_formattingStore removeRange:activeLink];
[self applyFormatting];
[self emitFormattingChanged];
}
- (void)showLinkPrompt
{
NSUInteger cursor = _textView.selectedRange.location;
ENRMFormattingRange *activeLink = [_formattingStore rangeOfType:ENRMInputStyleTypeLink containingPosition:cursor];
NSString *existingURL = activeLink != nil ? activeLink.url : nil;
__weak EnrichedMarkdownInput *weakSelf = self;
ENRMShowLinkPrompt(self, existingURL, ^(NSString *url) { [weakSelf setLink:url]; });
}
- (nullable NSString *)markdownForSelectedRange
{
NSRange selection = _textView.selectedRange;
if (selection.length == 0) {
return nil;
}
NSString *fullText = ENRMGetPlainText(_textView);
NSString *selectedText = [fullText substringWithRange:selection];
NSUInteger selEnd = NSMaxRange(selection);
NSMutableArray<ENRMFormattingRange *> *clippedRanges = [NSMutableArray array];
for (ENRMFormattingRange *range in [self allRangesIncludingTransient]) {
NSUInteger rangeStart = range.range.location;
NSUInteger rangeEnd = NSMaxRange(range.range);
if (rangeEnd <= selection.location || rangeStart >= selEnd) {
continue;
}
NSUInteger clippedStart = MAX(rangeStart, selection.location);
NSUInteger clippedEnd = MIN(rangeEnd, selEnd);
NSRange shifted = NSMakeRange(clippedStart - selection.location, clippedEnd - clippedStart);
[clippedRanges addObject:[ENRMFormattingRange rangeWithType:range.type range:shifted url:range.url]];
}
return [ENRMMarkdownSerializer serializePlainText:selectedText ranges:clippedRanges];
}
- (void)requestMarkdown:(NSInteger)requestId
{
auto emitter = [self getEventEmitter];
if (emitter == nullptr) {
return;
}
NSString *markdown = [ENRMMarkdownSerializer serializePlainText:ENRMGetPlainText(_textView)
ranges:[self allRangesIncludingTransient]];
emitter->onRequestMarkdownResult({
.requestId = static_cast<int>(requestId),
.markdown = std::string([markdown UTF8String] ?: ""),
});
}
- (CGRect)computeCaretRect
{
CGRect caretRect = CGRectZero;
#if !TARGET_OS_OSX
UITextRange *selectedRange = _textView.selectedTextRange;
if (selectedRange != nil) {
caretRect = [_textView caretRectForPosition:selectedRange.start];
}
#else
NSRange selection = _textView.selectedRange;
if (selection.location != NSNotFound) {
NSRange glyphRange = [_textView.layoutManager glyphRangeForCharacterRange:NSMakeRange(selection.location, 0)
actualCharacterRange:NULL];
caretRect = [_textView.layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:_textView.textContainer];
caretRect.origin.x += _textView.textContainerInset.left;
caretRect.origin.y += _textView.textContainerInset.top;
}
#endif
return caretRect;
}
- (void)requestCaretRect:(NSInteger)requestId
{
auto emitter = [self getEventEmitter];
if (emitter == nullptr) {
return;
}
CGRect caretRect = [self computeCaretRect];
emitter->onRequestCaretRectResult({
.requestId = static_cast<int>(requestId),
.x = caretRect.origin.x,
.y = caretRect.origin.y,
.width = caretRect.size.width,
.height = caretRect.size.height,
});
}
- (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args
{
RCTEnrichedMarkdownInputHandleCommand(self, commandName, args);
}
#pragma mark - Style state query
- (BOOL)isEffectiveStyleActive:(ENRMInputStyleType)type atPosition:(NSUInteger)position
{
BOOL inRange = [_formattingStore isStyleActive:type atPosition:position];
NSNumber *key = @(type);
if ([_pendingStyleRemovals containsObject:key]) {
return NO;
}
if ([_pendingStyles containsObject:key]) {
return YES;
}
return inRange;
}
#pragma mark - Event emitters
- (void)emitFormattingChanged
{
[self emitOnChangeState];
if (_emitMarkdown) {
[self emitOnChangeMarkdown];
}
}
- (std::shared_ptr<EnrichedMarkdownInputEventEmitter const>)getEventEmitter
{
if (_eventEmitter == nullptr || _blockEmitting) {
return nullptr;
}
return std::static_pointer_cast<EnrichedMarkdownInputEventEmitter const>(_eventEmitter);
}
- (NSArray<ENRMFormattingRange *> *)allRangesIncludingTransient
{
NSArray<ENRMFormattingRange *> *transient = [_detectorPipeline allTransientFormattingRanges];
if (transient.count == 0) {
return _formattingStore.allRanges;
}
NSMutableArray<ENRMFormattingRange *> *merged = [_formattingStore.allRanges mutableCopy];
[merged addObjectsFromArray:transient];
return merged;
}
- (void)emitOnChangeText
{
auto emitter = [self getEventEmitter];
if (emitter == nullptr) {
return;
}
NSString *plainText = ENRMGetPlainText(_textView);
emitter->onChangeText({.value = std::string([plainText UTF8String] ?: "")});
}
- (void)emitOnChangeMarkdown
{
auto emitter = [self getEventEmitter];
if (emitter == nullptr) {
return;
}
NSString *markdown = [ENRMMarkdownSerializer serializePlainText:ENRMGetPlainText(_textView)
ranges:[self allRangesIncludingTransient]];
emitter->onChangeMarkdown({.value = std::string([markdown UTF8String] ?: "")});
}
- (void)emitOnChangeSelection
{
auto emitter = [self getEventEmitter];
if (emitter == nullptr) {
return;
}
NSRange selection = _textView.selectedRange;
emitter->onChangeSelection({
.start = static_cast<int>(selection.location),
.end = static_cast<int>(NSMaxRange(selection)),
});
}
- (void)emitOnChangeState
{
auto emitter = [self getEventEmitter];
if (emitter == nullptr) {
return;
}
NSUInteger cursor = _textView.selectedRange.location;
BOOL boldActive = [self isEffectiveStyleActive:ENRMInputStyleTypeStrong atPosition:cursor];
BOOL italicActive = [self isEffectiveStyleActive:ENRMInputStyleTypeEmphasis atPosition:cursor];
BOOL underlineActive = [self isEffectiveStyleActive:ENRMInputStyleTypeUnderline atPosition:cursor];
BOOL strikethroughActive = [self isEffectiveStyleActive:ENRMInputStyleTypeStrikethrough atPosition:cursor];
BOOL spoilerActive = [self isEffectiveStyleActive:ENRMInputStyleTypeSpoiler atPosition:cursor];
BOOL linkActive = [self isEffectiveStyleActive:ENRMInputStyleTypeLink atPosition:cursor];
if (_prevState.initialized && _prevState.bold == boldActive && _prevState.italic == italicActive &&
_prevState.underline == underlineActive && _prevState.strikethrough == strikethroughActive &&
_prevState.spoiler == spoilerActive && _prevState.link == linkActive) {
return;
}
_prevState.bold = boldActive;
_prevState.italic = italicActive;
_prevState.underline = underlineActive;
_prevState.strikethrough = strikethroughActive;
_prevState.spoiler = spoilerActive;
_prevState.link = linkActive;
_prevState.initialized = YES;
emitter->onChangeState({
.bold = {.isActive = boldActive},
.italic = {.isActive = italicActive},
.underline = {.isActive = underlineActive},
.strikethrough = {.isActive = strikethroughActive},
.spoiler = {.isActive = spoilerActive},
.link = {.isActive = linkActive},
});
}
- (void)emitCaretRectChangeIfNeeded
{
auto emitter = [self getEventEmitter];
if (emitter == nullptr) {
return;
}
CGRect caretRect = [self computeCaretRect];
if (_prevCaretRect.has_value() && CGRectEqualToRect(_prevCaretRect.value(), caretRect)) {
return;
}
_prevCaretRect = caretRect;
emitter->onCaretRectChange({
.x = caretRect.origin.x,
.y = caretRect.origin.y,
.width = caretRect.size.width,
.height = caretRect.size.height,
});
}
- (NSArray<NSString *> *)contextMenuItemTexts
{
return _contextMenuItemTexts ?: @[];
}
- (NSArray<NSString *> *)contextMenuItemIcons
{
return _contextMenuItemIcons ?: @[];
}
- (void)emitContextMenuItemPress:(NSString *)itemText
{
auto eventEmitter = [self getEventEmitter];
if (eventEmitter == nullptr) {
return;
}
NSRange selectedRange = _textView.selectedRange;
NSString *selectedText =
selectedRange.length > 0 ? [_textView.textStorage.string substringWithRange:selectedRange] : @"";
auto isActive = [&](ENRMInputStyleType type) -> BOOL {
if (selectedRange.length > 0) {
return [_formattingStore isStyleActive:type inRange:selectedRange];
}
return [self isEffectiveStyleActive:type atPosition:selectedRange.location];
};
BOOL boldActive = isActive(ENRMInputStyleTypeStrong);
BOOL italicActive = isActive(ENRMInputStyleTypeEmphasis);
BOOL underlineActive = isActive(ENRMInputStyleTypeUnderline);
BOOL strikethroughActive = isActive(ENRMInputStyleTypeStrikethrough);
BOOL spoilerActive = isActive(ENRMInputStyleTypeSpoiler);
BOOL linkActive = isActive(ENRMInputStyleTypeLink);
eventEmitter->onContextMenuItemPress({
.itemText = std::string(itemText.UTF8String),
.selectedText = std::string(selectedText.UTF8String),
.selectionStart = static_cast<int>(selectedRange.location),
.selectionEnd = static_cast<int>(NSMaxRange(selectedRange)),
.styleState =
{
.bold = {.isActive = boldActive},
.italic = {.isActive = italicActive},
.underline = {.isActive = underlineActive},
.strikethrough = {.isActive = strikethroughActive},
.spoiler = {.isActive = spoilerActive},
.link = {.isActive = linkActive},
},
});
}