This repository was archived by the owner on Oct 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathSLKTextView.m
More file actions
1156 lines (894 loc) · 35.5 KB
/
SLKTextView.m
File metadata and controls
1156 lines (894 loc) · 35.5 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
//
// SlackTextViewController
// https://github.com/slackhq/SlackTextViewController
//
// Copyright 2014-2016 Slack Technologies, Inc.
// Licence: MIT-Licence
//
#import "SLKTextView.h"
#import "SLKTextView+SLKAdditions.h"
#import "SLKUIConstants.h"
NSString * const SLKTextViewTextWillChangeNotification = @"SLKTextViewTextWillChangeNotification";
NSString * const SLKTextViewContentSizeDidChangeNotification = @"SLKTextViewContentSizeDidChangeNotification";
NSString * const SLKTextViewSelectedRangeDidChangeNotification = @"SLKTextViewSelectedRangeDidChangeNotification";
NSString * const SLKTextViewDidPasteItemNotification = @"SLKTextViewDidPasteItemNotification";
NSString * const SLKTextViewDidShakeNotification = @"SLKTextViewDidShakeNotification";
NSString * const SLKTextViewPastedItemContentType = @"SLKTextViewPastedItemContentType";
NSString * const SLKTextViewPastedItemMediaType = @"SLKTextViewPastedItemMediaType";
NSString * const SLKTextViewPastedItemData = @"SLKTextViewPastedItemData";
static NSString *const SLKTextViewGenericFormattingSelectorPrefix = @"slk_format_";
@interface SLKTextView ()
// The label used as placeholder
@property (nonatomic, strong) UILabel *placeholderLabel;
// The initial font point size, used for dynamic type calculations
@property (nonatomic) CGFloat initialFontSize;
// Used for moving the caret up/down
@property (nonatomic) UITextLayoutDirection verticalMoveDirection;
@property (nonatomic) CGRect verticalMoveStartCaretRect;
@property (nonatomic) CGRect verticalMoveLastCaretRect;
// Used for detecting if the scroll indicator was previously flashed
@property (nonatomic) BOOL didFlashScrollIndicators;
@property (nonatomic, strong) NSMutableArray *registeredFormattingTitles;
@property (nonatomic, strong) NSMutableArray *registeredFormattingSymbols;
@property (nonatomic, getter=isFormatting) BOOL formatting;
// The keyboard commands available for external keyboards
@property (nonatomic, strong) NSMutableDictionary *registeredKeyCommands;
@property (nonatomic, strong) NSMutableDictionary *registeredKeyCallbacks;
@end
@implementation SLKTextView
@dynamic delegate;
#pragma mark - Initialization
- (instancetype)initWithFrame:(CGRect)frame textContainer:(NSTextContainer *)textContainer
{
if (self = [super initWithFrame:frame textContainer:textContainer]) {
[self slk_commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
if (self = [super initWithCoder:coder]) {
[self slk_commonInit];
}
return self;
}
- (void)slk_commonInit
{
_pastableMediaTypes = SLKPastableMediaTypeNone;
_dynamicTypeEnabled = YES;
self.undoManagerEnabled = YES;
self.editable = YES;
self.selectable = YES;
self.scrollEnabled = YES;
self.scrollsToTop = NO;
self.directionalLockEnabled = YES;
self.dataDetectorTypes = UIDataDetectorTypeNone;
[self slk_registerNotifications];
[self addObserver:self forKeyPath:NSStringFromSelector(@selector(contentSize)) options:NSKeyValueObservingOptionNew context:NULL];
}
#pragma mark - UIView Overrides
- (CGSize)intrinsicContentSize
{
CGFloat height = self.font.lineHeight;
height += self.textContainerInset.top + self.textContainerInset.bottom;
return CGSizeMake(UIViewNoIntrinsicMetric, height);
}
+ (BOOL)requiresConstraintBasedLayout
{
return YES;
}
- (void)layoutIfNeeded
{
if (!self.window) {
return;
}
[super layoutIfNeeded];
}
- (void)layoutSubviews
{
[super layoutSubviews];
self.placeholderLabel.hidden = [self slk_shouldHidePlaceholder];
if (!self.placeholderLabel.hidden) {
[UIView performWithoutAnimation:^{
self.placeholderLabel.frame = [self slk_placeholderRectThatFits:self.bounds];
[self sendSubviewToBack:self.placeholderLabel];
}];
}
}
#pragma mark - Getters
- (UILabel *)placeholderLabel
{
if (!_placeholderLabel) {
_placeholderLabel = [UILabel new];
_placeholderLabel.clipsToBounds = NO;
_placeholderLabel.numberOfLines = 1;
_placeholderLabel.autoresizesSubviews = NO;
_placeholderLabel.font = self.font;
_placeholderLabel.backgroundColor = [UIColor clearColor];
_placeholderLabel.textColor = [UIColor lightGrayColor];
_placeholderLabel.hidden = YES;
_placeholderLabel.isAccessibilityElement = NO;
[self addSubview:_placeholderLabel];
}
return _placeholderLabel;
}
- (NSString *)placeholder
{
return self.placeholderLabel.text;
}
- (UIColor *)placeholderColor
{
return self.placeholderLabel.textColor;
}
- (UIFont *)placeholderFont
{
return self.placeholderLabel.font;
}
- (CGFloat)appropriateHeight
{
NSUInteger numberOfLines = self.numberOfLines > self.maxNumberOfLines ? self.maxNumberOfLines : self.numberOfLines;
CGFloat height = [self intrinsicContentSize].height;
height -= self.font.lineHeight;
height += roundf(self.font.lineHeight*numberOfLines);
return height;
}
- (NSUInteger)numberOfLines
{
CGSize contentSize = self.contentSize;
CGFloat contentHeight = contentSize.height;
contentHeight -= self.textContainerInset.top + self.textContainerInset.bottom;
NSUInteger lines = fabs(contentHeight/self.font.lineHeight);
// This helps preventing the content's height to be larger that the bounds' height
// Avoiding this way to have unnecessary scrolling in the text view when there is only 1 line of content
if (lines == 1 && contentSize.height > self.bounds.size.height) {
contentSize.height = self.bounds.size.height;
self.contentSize = contentSize;
}
// Let's fallback to the minimum line count
if (lines == 0) {
lines = 1;
}
return lines;
}
- (NSUInteger)maxNumberOfLines
{
NSUInteger numberOfLines = _maxNumberOfLines;
if (SLK_IS_LANDSCAPE) {
if ((SLK_IS_IPHONE4 || SLK_IS_IPHONE5)) {
numberOfLines = 2.0; // 2 lines max on smaller iPhones
}
else if (SLK_IS_IPHONE) {
numberOfLines /= 2.0; // Half size on larger iPhone
}
}
if (self.isDynamicTypeEnabled) {
NSString *contentSizeCategory = [[UIApplication sharedApplication] preferredContentSizeCategory];
CGFloat pointSizeDifference = SLKPointSizeDifferenceForCategory(contentSizeCategory);
CGFloat factor = pointSizeDifference/self.initialFontSize;
if (fabs(factor) > 0.75) {
factor = 0.75;
}
numberOfLines -= floorf(numberOfLines * factor); // Calculates a dynamic number of lines depending of the user preferred font size
}
return numberOfLines;
}
- (BOOL)isTypingSuggestionEnabled
{
return (self.autocorrectionType == UITextAutocorrectionTypeNo) ? NO : YES;
}
- (BOOL)isFormattingEnabled
{
return (self.registeredFormattingSymbols.count > 0) ? YES : NO;
}
// Returns only a supported pasted item
- (id)slk_pastedItem
{
NSString *contentType = [self slk_pasteboardContentType];
NSData *data = [[UIPasteboard generalPasteboard] dataForPasteboardType:contentType];
if (data && [data isKindOfClass:[NSData class]])
{
SLKPastableMediaType mediaType = SLKPastableMediaTypeFromNSString(contentType);
NSDictionary *userInfo = @{SLKTextViewPastedItemContentType: contentType,
SLKTextViewPastedItemMediaType: @(mediaType),
SLKTextViewPastedItemData: data};
return userInfo;
}
if ([[UIPasteboard generalPasteboard] URL]) {
return [[[UIPasteboard generalPasteboard] URL] absoluteString];
}
if ([[UIPasteboard generalPasteboard] string]) {
return [[UIPasteboard generalPasteboard] string];
}
return nil;
}
// Checks if any supported media found in the general pasteboard
- (BOOL)slk_isPasteboardItemSupported
{
if ([self slk_pasteboardContentType].length > 0) {
return YES;
}
return NO;
}
- (NSString *)slk_pasteboardContentType
{
NSArray *pasteboardTypes = [[UIPasteboard generalPasteboard] pasteboardTypes];
NSMutableArray *subpredicates = [NSMutableArray new];
for (NSString *type in [self slk_supportedMediaTypes]) {
[subpredicates addObject:[NSPredicate predicateWithFormat:@"SELF == %@", type]];
}
return [[pasteboardTypes filteredArrayUsingPredicate:[NSCompoundPredicate orPredicateWithSubpredicates:subpredicates]] firstObject];
}
- (NSArray *)slk_supportedMediaTypes
{
if (self.pastableMediaTypes == SLKPastableMediaTypeNone) {
return nil;
}
NSMutableArray *types = [NSMutableArray new];
if (self.pastableMediaTypes & SLKPastableMediaTypePNG) {
[types addObject:NSStringFromSLKPastableMediaType(SLKPastableMediaTypePNG)];
}
if (self.pastableMediaTypes & SLKPastableMediaTypeJPEG) {
[types addObject:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeJPEG)];
}
if (self.pastableMediaTypes & SLKPastableMediaTypeTIFF) {
[types addObject:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeTIFF)];
}
if (self.pastableMediaTypes & SLKPastableMediaTypeGIF) {
[types addObject:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeGIF)];
}
if (self.pastableMediaTypes & SLKPastableMediaTypeMOV) {
[types addObject:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeMOV)];
}
if (self.pastableMediaTypes & SLKPastableMediaTypePassbook) {
[types addObject:NSStringFromSLKPastableMediaType(SLKPastableMediaTypePassbook)];
}
if (self.pastableMediaTypes & SLKPastableMediaTypeImages) {
[types addObject:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeImages)];
}
return types;
}
NSString *NSStringFromSLKPastableMediaType(SLKPastableMediaType type)
{
if (type == SLKPastableMediaTypePNG) {
return @"public.png";
}
if (type == SLKPastableMediaTypeJPEG) {
return @"public.jpeg";
}
if (type == SLKPastableMediaTypeTIFF) {
return @"public.tiff";
}
if (type == SLKPastableMediaTypeGIF) {
return @"com.compuserve.gif";
}
if (type == SLKPastableMediaTypeMOV) {
return @"com.apple.quicktime";
}
if (type == SLKPastableMediaTypePassbook) {
return @"com.apple.pkpass";
}
if (type == SLKPastableMediaTypeImages) {
return @"com.apple.uikit.image";
}
return nil;
}
SLKPastableMediaType SLKPastableMediaTypeFromNSString(NSString *string)
{
if ([string isEqualToString:NSStringFromSLKPastableMediaType(SLKPastableMediaTypePNG)]) {
return SLKPastableMediaTypePNG;
}
if ([string isEqualToString:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeJPEG)]) {
return SLKPastableMediaTypeJPEG;
}
if ([string isEqualToString:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeTIFF)]) {
return SLKPastableMediaTypeTIFF;
}
if ([string isEqualToString:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeGIF)]) {
return SLKPastableMediaTypeGIF;
}
if ([string isEqualToString:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeMOV)]) {
return SLKPastableMediaTypeMOV;
}
if ([string isEqualToString:NSStringFromSLKPastableMediaType(SLKPastableMediaTypePassbook)]) {
return SLKPastableMediaTypePassbook;
}
if ([string isEqualToString:NSStringFromSLKPastableMediaType(SLKPastableMediaTypeImages)]) {
return SLKPastableMediaTypeImages;
}
return SLKPastableMediaTypeNone;
}
- (BOOL)isExpanding
{
if (self.numberOfLines >= self.maxNumberOfLines) {
return YES;
}
return NO;
}
- (BOOL)slk_shouldHidePlaceholder
{
if (self.placeholder.length == 0 || self.text.length > 0) {
return YES;
}
return NO;
}
- (CGRect)slk_placeholderRectThatFits:(CGRect)bounds
{
CGFloat padding = self.textContainer.lineFragmentPadding;
CGRect rect = CGRectZero;
rect.size.height = [self.placeholderLabel sizeThatFits:bounds.size].height;
rect.size.width = self.textContainer.size.width - padding*2.0;
rect.origin = UIEdgeInsetsInsetRect(bounds, self.textContainerInset).origin;
rect.origin.x += padding;
return rect;
}
#pragma mark - Setters
- (void)setPlaceholder:(NSString *)placeholder
{
self.placeholderLabel.text = placeholder;
self.accessibilityLabel = placeholder;
[self setNeedsLayout];
}
- (void)setPlaceholderColor:(UIColor *)color
{
self.placeholderLabel.textColor = color;
}
- (void)setPlaceholderNumberOfLines:(NSInteger)numberOfLines
{
self.placeholderLabel.numberOfLines = numberOfLines;
[self setNeedsLayout];
}
- (void)setPlaceholderFont:(UIFont *)placeholderFont
{
if (!placeholderFont) {
self.placeholderLabel.font = self.font;
}
else {
self.placeholderLabel.font = placeholderFont;
}
}
- (void)setUndoManagerEnabled:(BOOL)enabled
{
if (self.undoManagerEnabled == enabled) {
return;
}
self.undoManager.levelsOfUndo = 10;
[self.undoManager removeAllActions];
[self.undoManager setActionIsDiscardable:YES];
_undoManagerEnabled = enabled;
}
- (void)setTypingSuggestionEnabled:(BOOL)enabled
{
if (self.isTypingSuggestionEnabled == enabled) {
return;
}
self.autocorrectionType = enabled ? UITextAutocorrectionTypeDefault : UITextAutocorrectionTypeNo;
self.spellCheckingType = enabled ? UITextSpellCheckingTypeDefault : UITextSpellCheckingTypeNo;
[self refreshFirstResponder];
}
- (void)setContentOffset:(CGPoint)contentOffset
{
// At times during a layout pass, the content offset's x value may change.
// Since we only care about vertical offset, let's override its horizontal value to avoid other layout issues.
[super setContentOffset:CGPointMake(0.0, contentOffset.y)];
}
#pragma mark - UITextView Overrides
- (void)setSelectedRange:(NSRange)selectedRange
{
[super setSelectedRange:selectedRange];
[[NSNotificationCenter defaultCenter] postNotificationName:SLKTextViewSelectedRangeDidChangeNotification object:self userInfo:nil];
}
- (void)setSelectedTextRange:(UITextRange *)selectedTextRange
{
[super setSelectedTextRange:selectedTextRange];
[[NSNotificationCenter defaultCenter] postNotificationName:SLKTextViewSelectedRangeDidChangeNotification object:self userInfo:nil];
}
- (void)setText:(NSString *)text
{
// Registers for undo management
[self slk_prepareForUndo:@"Text Set"];
if (text) {
[self setAttributedText:[self slk_defaultAttributedStringForText:text]];
}
else {
[self setAttributedText:nil];
}
[[NSNotificationCenter defaultCenter] postNotificationName:UITextViewTextDidChangeNotification object:self];
}
- (NSString *)text
{
return self.attributedText.string;
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
// Registers for undo management
[self slk_prepareForUndo:@"Attributed Text Set"];
[super setAttributedText:attributedText];
[[NSNotificationCenter defaultCenter] postNotificationName:UITextViewTextDidChangeNotification object:self];
}
- (void)setFont:(UIFont *)font
{
NSString *contentSizeCategory = [[UIApplication sharedApplication] preferredContentSizeCategory];
[self setFontName:font.fontName pointSize:font.pointSize withContentSizeCategory:contentSizeCategory];
self.initialFontSize = font.pointSize;
}
- (void)setFontName:(NSString *)fontName pointSize:(CGFloat)pointSize withContentSizeCategory:(NSString *)contentSizeCategory
{
if (self.isDynamicTypeEnabled) {
pointSize += SLKPointSizeDifferenceForCategory(contentSizeCategory);
}
UIFont *dynamicFont = [UIFont fontWithName:fontName size:pointSize];
[super setFont:dynamicFont];
// Updates the placeholder font too
self.placeholderLabel.font = dynamicFont;
}
- (void)setDynamicTypeEnabled:(BOOL)dynamicTypeEnabled
{
if (self.isDynamicTypeEnabled == dynamicTypeEnabled) {
return;
}
_dynamicTypeEnabled = dynamicTypeEnabled;
NSString *contentSizeCategory = [[UIApplication sharedApplication] preferredContentSizeCategory];
[self setFontName:self.font.fontName pointSize:self.initialFontSize withContentSizeCategory:contentSizeCategory];
}
- (void)setTextAlignment:(NSTextAlignment)textAlignment
{
[super setTextAlignment:textAlignment];
// Updates the placeholder text alignment too
self.placeholderLabel.textAlignment = textAlignment;
}
#pragma mark - UITextInput Overrides
#ifdef __IPHONE_9_0
- (void)beginFloatingCursorAtPoint:(CGPoint)point
{
[super beginFloatingCursorAtPoint:point];
_trackpadEnabled = YES;
}
- (void)updateFloatingCursorAtPoint:(CGPoint)point
{
[super updateFloatingCursorAtPoint:point];
}
- (void)endFloatingCursor
{
[super endFloatingCursor];
_trackpadEnabled = NO;
// We still need to notify a selection change in the textview after the trackpad is disabled
if (self.delegate && [self.delegate respondsToSelector:@selector(textViewDidChangeSelection:)]) {
[self.delegate textViewDidChangeSelection:self];
}
[[NSNotificationCenter defaultCenter] postNotificationName:SLKTextViewSelectedRangeDidChangeNotification object:self userInfo:nil];
}
#endif
#pragma mark - UIResponder Overrides
- (BOOL)canBecomeFirstResponder
{
[self slk_addCustomMenuControllerItems];
return [super canBecomeFirstResponder];
}
- (BOOL)becomeFirstResponder
{
return [super becomeFirstResponder];
}
- (BOOL)canResignFirstResponder
{
// Removes undo/redo items
if (self.undoManagerEnabled) {
[self.undoManager removeAllActions];
}
return [super canResignFirstResponder];
}
- (BOOL)resignFirstResponder
{
return [super resignFirstResponder];
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (self.isFormatting) {
NSString *title = [self slk_formattingTitleFromSelector:action];
NSString *symbol = [self slk_formattingSymbolWithTitle:title];
if (symbol.length > 0) {
if (self.delegate && [self.delegate respondsToSelector:@selector(textView:shouldOfferFormattingForSymbol:)]) {
return [self.delegate textView:self shouldOfferFormattingForSymbol:symbol];
}
else {
return YES;
}
}
return NO;
}
if (action == @selector(delete:)) {
return NO;
}
if (action == @selector(slk_presentFormattingMenu:)) {
return self.selectedRange.length > 0 ? YES : NO;
}
if (action == @selector(paste:) && [self slk_isPasteboardItemSupported]) {
return YES;
}
if (self.undoManagerEnabled) {
if (action == @selector(slk_undo:)) {
if (self.undoManager.undoActionIsDiscardable) {
return NO;
}
return [self.undoManager canUndo];
}
if (action == @selector(slk_redo:)) {
if (self.undoManager.redoActionIsDiscardable) {
return NO;
}
return [self.undoManager canRedo];
}
}
return [super canPerformAction:action withSender:sender];
}
- (void)paste:(id)sender
{
id pastedItem = [self slk_pastedItem];
if ([pastedItem isKindOfClass:[NSDictionary class]]) {
[[NSNotificationCenter defaultCenter] postNotificationName:SLKTextViewDidPasteItemNotification object:nil userInfo:pastedItem];
}
else if ([pastedItem isKindOfClass:[NSString class]]) {
// Respect the delegate yo!
if (self.delegate && [self.delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) {
if (![self.delegate textView:self shouldChangeTextInRange:self.selectedRange replacementText:pastedItem]) {
return;
}
}
// Inserting the text fixes a UITextView bug whitch automatically scrolls to the bottom
// and beyond scroll content size sometimes when the text is too long
[self slk_insertTextAtCaretRange:pastedItem];
}
}
#pragma mark - NSObject Overrides
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
if ([super methodSignatureForSelector:sel]) {
return [super methodSignatureForSelector:sel];
}
return [super methodSignatureForSelector:@selector(slk_format:)];
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
NSString *title = [self slk_formattingTitleFromSelector:[invocation selector]];
if (title.length > 0) {
[self slk_format:title];
}
else {
[super forwardInvocation:invocation];
}
}
#pragma mark - Custom Actions
- (void)slk_flashScrollIndicatorsIfNeeded
{
if (self.numberOfLines == self.maxNumberOfLines+1) {
if (!_didFlashScrollIndicators) {
_didFlashScrollIndicators = YES;
[super flashScrollIndicators];
}
}
else if (_didFlashScrollIndicators) {
_didFlashScrollIndicators = NO;
}
}
- (void)refreshFirstResponder
{
if (!self.isFirstResponder) {
return;
}
_didNotResignFirstResponder = YES;
[self resignFirstResponder];
_didNotResignFirstResponder = NO;
[self becomeFirstResponder];
}
- (void)refreshInputViews
{
_didNotResignFirstResponder = YES;
[super reloadInputViews];
_didNotResignFirstResponder = NO;
}
- (void)slk_addCustomMenuControllerItems
{
UIMenuItem *undo = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"Undo", nil) action:@selector(slk_undo:)];
UIMenuItem *redo = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"Redo", nil) action:@selector(slk_redo:)];
NSMutableArray *items = [NSMutableArray arrayWithObjects:undo, redo, nil];
if (self.registeredFormattingTitles.count > 0) {
UIMenuItem *format = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"Format", nil) action:@selector(slk_presentFormattingMenu:)];
[items addObject:format];
}
[[UIMenuController sharedMenuController] setMenuItems:items];
}
- (void)slk_undo:(id)sender
{
[self.undoManager undo];
}
- (void)slk_redo:(id)sender
{
[self.undoManager redo];
}
- (void)slk_presentFormattingMenu:(id)sender
{
NSMutableArray *items = [NSMutableArray arrayWithCapacity:self.registeredFormattingTitles.count];
for (NSString *name in self.registeredFormattingTitles) {
NSString *sel = [NSString stringWithFormat:@"%@%@", SLKTextViewGenericFormattingSelectorPrefix, name];
UIMenuItem *item = [[UIMenuItem alloc] initWithTitle:name action:NSSelectorFromString(sel)];
[items addObject:item];
}
self.formatting = YES;
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:items];
NSLayoutManager *manager = self.layoutManager;
CGRect targetRect = [manager boundingRectForGlyphRange:self.selectedRange inTextContainer:self.textContainer];
[menu setTargetRect:targetRect inView:self];
[menu setMenuVisible:YES animated:YES];
}
- (NSString *)slk_formattingTitleFromSelector:(SEL)selector
{
NSString *selectorString = NSStringFromSelector(selector);
NSRange match = [selectorString rangeOfString:SLKTextViewGenericFormattingSelectorPrefix];
if (match.location != NSNotFound) {
return [selectorString substringFromIndex:SLKTextViewGenericFormattingSelectorPrefix.length];
}
return nil;
}
- (NSString *)slk_formattingSymbolWithTitle:(NSString *)title
{
NSUInteger idx = [self.registeredFormattingTitles indexOfObject:title];
if (idx <= self.registeredFormattingSymbols.count -1) {
return self.registeredFormattingSymbols[idx];
}
return nil;
}
- (void)slk_format:(NSString *)titles
{
NSString *symbol = [self slk_formattingSymbolWithTitle:titles];
if (symbol.length > 0) {
NSRange selection = self.selectedRange;
NSRange range = [self slk_insertText:symbol inRange:NSMakeRange(selection.location, 0)];
range.location += selection.length;
range.length = 0;
// The default behavior is to add a closure
BOOL addClosure = YES;
if (self.delegate && [self.delegate respondsToSelector:@selector(textView:shouldInsertSuffixForFormattingWithSymbol:prefixRange:)]) {
addClosure = [self.delegate textView:self shouldInsertSuffixForFormattingWithSymbol:symbol prefixRange:selection];
}
if (addClosure) {
self.selectedRange = [self slk_insertText:symbol inRange:range];
}
}
}
#pragma mark - Markdown Formatting
- (void)registerMarkdownFormattingSymbol:(NSString *)symbol withTitle:(NSString *)title
{
if (!symbol || !title) {
return;
}
if (!_registeredFormattingTitles) {
_registeredFormattingTitles = [NSMutableArray new];
_registeredFormattingSymbols = [NSMutableArray new];
}
// Adds the symbol if not contained already
if (![self.registeredSymbols containsObject:symbol]) {
[self.registeredFormattingTitles addObject:title];
[self.registeredFormattingSymbols addObject:symbol];
}
}
- (NSArray *)registeredSymbols
{
return self.registeredFormattingSymbols;
}
#pragma mark - Notification Events
- (void)slk_didBeginEditing:(NSNotification *)notification
{
if (![notification.object isEqual:self]) {
return;
}
// Do something
}
- (void)slk_didChangeText:(NSNotification *)notification
{
if (![notification.object isEqual:self]) {
return;
}
if (self.placeholderLabel.hidden != [self slk_shouldHidePlaceholder]) {
[self setNeedsLayout];
}
[self slk_flashScrollIndicatorsIfNeeded];
}
- (void)slk_didEndEditing:(NSNotification *)notification
{
if (![notification.object isEqual:self]) {
return;
}
// Do something
}
- (void)slk_didChangeTextInputMode:(NSNotification *)notification
{
// Do something
}
- (void)slk_didChangeContentSizeCategory:(NSNotification *)notification
{
if (!self.isDynamicTypeEnabled) {
return;
}
NSString *contentSizeCategory = notification.userInfo[UIContentSizeCategoryNewValueKey];
[self setFontName:self.font.fontName pointSize:self.initialFontSize withContentSizeCategory:contentSizeCategory];
NSString *text = [self.text copy];
// Reloads the content size of the text view
[self setText:@" "];
[self setText:text];
}
- (void)slk_willShowMenuController:(NSNotification *)notification
{
// Do something
}
- (void)slk_didHideMenuController:(NSNotification *)notification
{
self.formatting = NO;
[self slk_addCustomMenuControllerItems];
}
#pragma mark - KVO Listener
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([object isEqual:self] && [keyPath isEqualToString:NSStringFromSelector(@selector(contentSize))]) {
[[NSNotificationCenter defaultCenter] postNotificationName:SLKTextViewContentSizeDidChangeNotification object:self userInfo:nil];
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark - Motion Events
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) {
[[NSNotificationCenter defaultCenter] postNotificationName:SLKTextViewDidShakeNotification object:self];
}
}
#pragma mark - External Keyboard Support
typedef void (^SLKKeyCommandHandler)(UIKeyCommand *keyCommand);
- (void)observeKeyInput:(NSString *)input modifiers:(UIKeyModifierFlags)modifiers title:(NSString *_Nullable)title completion:(void (^)(UIKeyCommand *keyCommand))completion
{
NSAssert([input isKindOfClass:[NSString class]], @"You must provide a string with one or more characters corresponding to the keys to observe.");
NSAssert(completion != nil, @"You must provide a non-nil completion block.");
if (!input || !completion) {
return;
}
UIKeyCommand *keyCommand = [UIKeyCommand keyCommandWithInput:input modifierFlags:modifiers action:@selector(didDetectKeyCommand:)];
#ifdef __IPHONE_9_0
if ([UIKeyCommand respondsToSelector:@selector(keyCommandWithInput:modifierFlags:action:discoverabilityTitle:)] ) {
keyCommand.discoverabilityTitle = title;
}
#endif
if (!_registeredKeyCommands) {
_registeredKeyCommands = [NSMutableDictionary new];
_registeredKeyCallbacks = [NSMutableDictionary new];
}
NSString *key = [self keyForKeyCommand:keyCommand];
self.registeredKeyCommands[key] = keyCommand;
self.registeredKeyCallbacks[key] = completion;
}
- (void)didDetectKeyCommand:(UIKeyCommand *)keyCommand
{
NSString *key = [self keyForKeyCommand:keyCommand];
SLKKeyCommandHandler completion = self.registeredKeyCallbacks[key];