-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathTextView.swift
2285 lines (1821 loc) · 84.6 KB
/
TextView.swift
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 UIKit
import Foundation
import CoreServices
// MARK: - TextViewAttachmentDelegate
//
public protocol TextViewAttachmentDelegate: class {
/// This method requests from the delegate the image at the specified URL.
///
/// - Parameters:
/// - textView: the `TextView` the call has been made from.
/// - attachment: the attachment that is requesting the image
/// - imageURL: the url to download the image from.
/// - success: when the image is obtained, this closure should be executed.
/// - failure: if the image cannot be obtained, this closure should be executed.
///
func textView(_ textView: TextView,
attachment: NSTextAttachment,
imageAt url: URL,
onSuccess success: @escaping (UIImage) -> Void,
onFailure failure: @escaping () -> Void)
/// Called when an attachment is about to be added to the storage as an attachment (copy/paste), so that the
/// delegate can specify an URL where that attachment is available.
///
/// - Parameters:
/// - textView: The textView that is requesting the image.
/// - imageAttachment: The image attachment that was added to the storage.
///
/// - Returns: the requested `URL` where the image is stored, or nil if it's not yet available.
///
func textView(_ textView: TextView, urlFor imageAttachment: ImageAttachment) -> URL?
/// Called when an attachment doesn't have an available source URL to provide an image representation.
///
/// - Parameters:
/// - textView: the textview that is requesting the image
/// - attachment: the attachment that does not an have image source
///
/// - Returns: an UIImage to represent the attachment graphically
///
func textView(_ textView: TextView, placeholderFor attachment: NSTextAttachment) -> UIImage
/// Called after a attachment is removed from the storage.
///
/// - Parameters:
/// - textView: The textView where the attachment was removed.
/// - attachment: The media attachment that was removed.
///
func textView(_ textView: TextView, deletedAttachment attachment: MediaAttachment)
/// Called after an attachment is selected with a single tap.
///
/// - Parameters:
/// - textView: the textview where the attachment is.
/// - attachment: the attachment that was selected.
/// - position: touch position relative to the textview.
///
func textView(_ textView: TextView, selected attachment: NSTextAttachment, atPosition position: CGPoint)
/// Called after an attachment is deselected with a single tap.
///
/// - Parameters:
/// - textView: the textview where the attachment is.
/// - attachment: the attachment that was deselected.
/// - position: touch position relative to the textView
///
func textView(_ textView: TextView, deselected attachment: NSTextAttachment, atPosition position: CGPoint)
}
// MARK: - TextViewAttachmentImageProvider
//
public protocol TextViewAttachmentImageProvider: class {
/// Indicates whether the current Attachment Renderer supports a given NSTextAttachment instance, or not.
///
/// - Parameters:
/// - textView: The textView that is requesting the bounds.
/// - attachment: Attachment about to be rendered.
///
/// - Returns: True when supported, false otherwise.
///
func textView(_ textView: TextView, shouldRender attachment: NSTextAttachment) -> Bool
/// Provides the Bounds required to represent a given attachment, within a specified line fragment.
///
/// - Parameters:
/// - textView: The textView that is requesting the bounds.
/// - attachment: Attachment about to be rendered.
/// - lineFragment: Line Fragment in which the glyph would be rendered.
///
/// - Returns: Rect specifying the Bounds for the comment attachment
///
func textView(_ textView: TextView, boundsFor attachment: NSTextAttachment, with lineFragment: CGRect) -> CGRect
/// Provides the (Optional) Image Representation of the specified size, for a given Attachment.
///
/// - Parameters:
/// - textView: The textView that is requesting the bounds.
/// - attachment: Attachment about to be rendered.
/// - size: Expected Image Size
///
/// - Returns: (Optional) UIImage representation of the Comment Attachment.
///
func textView(_ textView: TextView, imageFor attachment: NSTextAttachment, with size: CGSize) -> UIImage?
}
// MARK: - TextViewFormattingDelegate
//
public protocol TextViewFormattingDelegate: class {
/// Called a text view command toggled a style.
///
/// If you have a format bar, you should probably update it here.
///
func textViewCommandToggledAStyle()
}
// MARK: - TextViewPasteboardDelegate
//
public protocol TextViewPasteboardDelegate: class {
/// Called by the TextView when it's attempting to paste the contents of the pasteboard.
///
/// - Returns: True if the paste succeeded, false if it did not.
func tryPasting(in textView: TextView) -> Bool
/// Called by the TextView when it's attempting to paste a URL.
///
/// - Returns: True if the paste succeeded, false if it did not.
func tryPastingURL(in textView: TextView) -> Bool
/// Called by the TextView when it's attempting to paste HTML content.
///
/// - Returns: True if the paste succeeded, false if it did not.
func tryPastingHTML(in textView: TextView) -> Bool
/// Called by the TextView when it's attempting to paste an attributed string.
///
/// - Returns: True if the paste succeeded, false if it did not.
func tryPastingAttributedString(in textView: TextView) -> Bool
/// Called by the TextView when it's attempting to paste a string.
///
/// - Returns: True if the paste succeeded, false if it did not.
func tryPastingString(in textView: TextView) -> Bool
}
// MARK: - TextView
//
open class TextView: UITextView {
// MARK: - Aztec Delegates
/// The media delegate takes care of providing remote media when requested by the `TextView`.
/// If this is not set, all remove images will be left blank.
///
open weak var textAttachmentDelegate: TextViewAttachmentDelegate?
/// Maintains a reference to the user provided Text Attachment Image Providers
///
fileprivate var textAttachmentImageProvider = [TextViewAttachmentImageProvider]()
/// Formatting Delegate: to be used by the Edition's Format Bar.
///
open weak var formattingDelegate: TextViewFormattingDelegate?
/// Pasteboard Delegate: Handles Cut, Copy, and Paste commands. Can be overridden
/// by a subclass to customize behaviour.
///
open var pasteboardDelegate: TextViewPasteboardDelegate = AztecTextViewPasteboardDelegate()
/// If this is true the text view will notify is delegate and notification system when changes happen by calls to methods like setHTML
///
open var shouldNotifyOfNonUserChanges = true
// MARK: - Customizable Input VC
private var customInputViewController: UIInputViewController?
open override var inputViewController: UIInputViewController? {
get {
return customInputViewController
}
set {
customInputViewController = newValue
}
}
// MARK: - Behavior configuration
private static let singleLineParagraphFormatters: [AttributeFormatter] = [
HeaderFormatter(headerLevel: .h1),
HeaderFormatter(headerLevel: .h2),
HeaderFormatter(headerLevel: .h3),
HeaderFormatter(headerLevel: .h4),
HeaderFormatter(headerLevel: .h5),
HeaderFormatter(headerLevel: .h6),
FigureFormatter(),
FigcaptionFormatter(),
]
/// At some point moving ahead, this could be dynamically generated from the full list of registered formatters
///
private lazy var paragraphFormatters: [ParagraphAttributeFormatter] = [
BlockquoteFormatter(),
HeaderFormatter(headerLevel:.h1),
HeaderFormatter(headerLevel:.h2),
HeaderFormatter(headerLevel:.h3),
HeaderFormatter(headerLevel:.h4),
HeaderFormatter(headerLevel:.h5),
HeaderFormatter(headerLevel:.h6),
PreFormatter(placeholderAttributes: self.defaultAttributes),
TextListFormatter(style: .ordered),
TextListFormatter(style: .unordered),
]
// MARK: - Properties: Text Lists
var maximumListIndentationLevels = 7
// MARK: - Properties: Blockquotes
/// The max levels of quote indentation allowed
/// Default is 9
public var maximumBlockquoteIndentationLevels = 9
// MARK: - Properties: UI Defaults
/// The font to use to render any HTML that doesn't specify an explicit font.
/// If this is changed all the instances that use this font will be updated to the new one.
public var defaultFont: UIFont {
didSet {
textStorage.replace(font: oldValue, with: defaultFont)
}
}
public let defaultParagraphStyle: ParagraphStyle
var defaultMissingImage: UIImage
fileprivate var defaultAttributes: [NSAttributedString.Key: Any] {
var attributes: [NSAttributedString.Key: Any] = [
.font: defaultFont,
.paragraphStyle: defaultParagraphStyle,
]
if let color = defaultTextColor {
attributes[.foregroundColor] = color
}
return attributes
}
open lazy var defaultTextColor: UIColor? = {
if #available(iOS 13.0, *) {
return UIColor.label
} else {
return UIColor.darkText
}
}()
open override var textColor: UIColor? {
set {
super.textColor = newValue
defaultTextColor = newValue
}
get {
return super.textColor
}
}
// MARK: - Plugin Loading
var pluginManager: PluginManager {
get {
return storage.pluginManager
}
}
public func load(_ plugin: Plugin) {
pluginManager.load(plugin, in: self)
}
// MARK: - TextKit Aztec Subclasses
public var storage: TextStorage {
return textStorage as! TextStorage
}
var layout: LayoutManager {
return layoutManager as! LayoutManager
}
// MARK: - Apparance Properties
/// Blockquote Blocks Border and Text Colors
///
@objc dynamic public var blockquoteBorderColors: [UIColor] {
get {
return layout.blockquoteBorderColors
}
set {
layout.blockquoteBorderColors = newValue
}
}
/// Blockquote Blocks Background Color.
///
@objc dynamic public var blockquoteBackgroundColor: UIColor? {
get {
return layout.blockquoteBackgroundColor
}
set {
layout.blockquoteBackgroundColor = newValue
}
}
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if #available(iOS 13.0, *) {
if let previous = previousTraitCollection, previous.hasDifferentColorAppearance(comparedTo: traitCollection) {
self.refreshMediaAttachments()
}
}
}
/// Blockquote Blocks Background Width.
///
@objc dynamic public var blockquoteBorderWidth: CGFloat {
get {
return layout.blockquoteBorderWidth
}
set {
layout.blockquoteBorderWidth = newValue
}
}
/// Pre Blocks Background Color.
///
@objc dynamic public var preBackgroundColor: UIColor? {
get {
return layout.preBackgroundColor
}
set {
layout.preBackgroundColor = newValue
}
}
// MARK: - Overwritten Properties
/// The reason why we need to use this, instead of `super.typingAttributes`, is that iOS seems to sometimes
/// modify `super.typingAttributes` without us having any mechanism to intercept those changes.
///
private var myTypingAttributes = [NSAttributedString.Key: Any]()
override open var typingAttributes: [NSAttributedString.Key: Any] {
get {
return myTypingAttributes
}
set {
// We're still setting the parent's typing attributes in case they're used directly
// by any iOS feature.
super.typingAttributes = newValue
myTypingAttributes = newValue
}
}
override open var textAlignment: NSTextAlignment {
didSet {
if (textAlignment != oldValue) {
recalculateTypingAttributes()
}
}
}
/// This property returns the Attributes associated to the Extra Line Fragment.
///
public var extraLineFragmentTypingAttributes: [NSAttributedString.Key: Any] {
guard selectedTextRange?.start != endOfDocument else {
return typingAttributes
}
let string = textStorage.string
guard !string.isEndOfParagraph(before: string.endIndex) else {
return defaultAttributes
}
let lastLocation = max(string.count - 1, 0)
return textStorage.attributes(at: lastLocation, effectiveRange: nil)
}
// MARK: - Init & deinit
/// Creates a Text View using the provided parameters as a base for HTML rendering.
/// - Parameter defaultFont: The font to use to render the elements if no specific font is set by the HTML.
/// - Parameter defaultParagraphStyle: The default paragraph style if no explicit attributes are defined in HTML
/// - Parameter defaultMissingImage: The image to use if the view is not able to render an image specified in the HTML.
@objc public init(
defaultFont: UIFont,
defaultParagraphStyle: ParagraphStyle = ParagraphStyle.default,
defaultMissingImage: UIImage) {
self.defaultFont = UIFontMetrics.default.scaledFont(for: defaultFont)
self.defaultParagraphStyle = defaultParagraphStyle
self.defaultMissingImage = defaultMissingImage
let storage = TextStorage()
let layoutManager = LayoutManager()
let container = NSTextContainer()
container.widthTracksTextView = true
storage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(container)
super.init(frame: CGRect(x: 0, y: 0, width: 10, height: 10), textContainer: container)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
defaultFont = FontProvider.shared.defaultFont
defaultParagraphStyle = ParagraphStyle.default
defaultMissingImage = Assets.imageIcon
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
allowsEditingTextAttributes = true
adjustsFontForContentSizeCategory = true
storage.attachmentsDelegate = self
font = defaultFont
linkTextAttributes = [.underlineStyle: NSNumber(value: NSUnderlineStyle.single.rawValue), .foregroundColor: tintColor as Any]
typingAttributes = defaultAttributes
setupMenuController()
setupAttachmentTouchDetection()
setupLayoutManager()
}
private func setupMenuController() {
let pasteAndMatchTitle = NSLocalizedString("Paste without Formatting", comment: "Paste without Formatting Menu Item")
let pasteAndMatchItem = UIMenuItem(title: pasteAndMatchTitle, action: #selector(pasteWithoutFormatting))
UIMenuController.shared.menuItems = [pasteAndMatchItem]
}
fileprivate lazy var recognizerDelegate: AttachmentGestureRecognizerDelegate = {
return AttachmentGestureRecognizerDelegate(textView: self)
}()
fileprivate lazy var attachmentGestureRecognizer: UITapGestureRecognizer = { [unowned self] in
let attachmentGestureRecognizer = UITapGestureRecognizer(target: self.recognizerDelegate, action: #selector(AttachmentGestureRecognizerDelegate.richTextViewWasPressed))
attachmentGestureRecognizer.cancelsTouchesInView = true
attachmentGestureRecognizer.delaysTouchesBegan = true
attachmentGestureRecognizer.delaysTouchesEnded = true
attachmentGestureRecognizer.delegate = self.recognizerDelegate
return attachmentGestureRecognizer
}()
private func setupAttachmentTouchDetection() {
for gesture in gestureRecognizers ?? [] {
gesture.require(toFail: attachmentGestureRecognizer)
}
addGestureRecognizer(attachmentGestureRecognizer)
}
private func setupLayoutManager() {
guard let aztecLayoutManager = layoutManager as? LayoutManager else {
return
}
aztecLayoutManager.extraLineFragmentTypingAttributes = { [weak self] in
return self?.extraLineFragmentTypingAttributes ?? [:]
}
}
// MARK: - Intercept copy paste operations
open override func cut(_ sender: Any?) {
let data = storage.attributedSubstring(from: selectedRange).archivedData()
let html = storage.getHTML(range: selectedRange)
super.cut(sender)
storeInPasteboard(encoded: data)
storeInPasteboard(html: html)
}
open override func copy(_ sender: Any?) {
let data = storage.attributedSubstring(from: selectedRange).archivedData()
let html = storage.getHTML(range: selectedRange)
super.copy(sender)
storeInPasteboard(encoded: data)
storeInPasteboard(html: html)
}
open override func paste(_ sender: Any?) {
guard pasteboardDelegate.tryPasting(in: self) else {
super.paste(sender)
return
}
}
@objc open func pasteWithoutFormatting(_ sender: Any?) {
guard pasteboardDelegate.tryPastingString(in: self) else {
super.paste(sender)
return
}
}
// MARK: - Intercept Keystrokes
public lazy var carriageReturnKeyCommand: UIKeyCommand = {
return UIKeyCommand(input: String(.carriageReturn), modifierFlags: .shift, action: #selector(handleShiftEnter(command:)))
}()
public lazy var tabKeyCommand: UIKeyCommand = {
return UIKeyCommand(input: String(.tab), modifierFlags: [], action: #selector(handleTab(command:)))
}()
public lazy var shiftTabKeyCommand: UIKeyCommand = {
return UIKeyCommand(input: String(.tab), modifierFlags: .shift, action: #selector(handleShiftTab(command:)))
}()
override open var keyCommands: [UIKeyCommand]? {
get {
// When the keyboard "enter" key is pressed, the keycode corresponds to .carriageReturn,
// even if it's later converted to .lineFeed by default.
//
return [
carriageReturnKeyCommand,
shiftTabKeyCommand,
tabKeyCommand,
]
}
}
@objc func handleShiftEnter(command: UIKeyCommand) {
insertText(String(.lineSeparator))
}
@objc func handleShiftTab(command: UIKeyCommand) {
let lists = TextListFormatter.lists(in: typingAttributes)
let quotes = BlockquoteFormatter.blockquotes(in: typingAttributes)
if let list = lists.last {
indent(list: list, increase: false)
} else if let quote = quotes.last {
indent(blockquote: quote, increase: false)
} else {
return
}
}
@objc func handleTab(command: UIKeyCommand) {
let lists = TextListFormatter.lists(in: typingAttributes)
let quotes = BlockquoteFormatter.blockquotes(in: typingAttributes)
if let list = lists.last, lists.count < maximumListIndentationLevels {
indent(list: list)
} else if let quote = quotes.last, quotes.count < maximumBlockquoteIndentationLevels {
indent(blockquote: quote)
} else {
insertText(String(.tab))
}
}
// MARK: - Text List indent methods
private func indent(list: TextList, increase: Bool = true) {
let formatter = TextListFormatter(style: list.style, placeholderAttributes: nil, increaseDepth: true)
let li = LiFormatter(placeholderAttributes: nil)
let targetRange = formatter.applicationRange(for: selectedRange, in: storage)
performUndoable(at: targetRange) {
let finalRange: NSRange
if increase {
finalRange = increaseIndent(listFormatter: formatter, liFormatter: li, targetRange: targetRange)
} else {
finalRange = decreaseIndent(listFormatter: formatter, liFormatter: li, targetRange: targetRange)
}
typingAttributes = textStorage.attributes(at: targetRange.location, effectiveRange: nil)
return finalRange
}
}
// MARK: Text List increase or decrease indentation
private func increaseIndent(listFormatter: TextListFormatter, liFormatter: LiFormatter, targetRange: NSRange) -> NSRange {
let finalRange = listFormatter.applyAttributes(to: storage, at: targetRange)
liFormatter.applyAttributes(to: storage, at: targetRange)
return finalRange
}
private func decreaseIndent(listFormatter: TextListFormatter, liFormatter: LiFormatter, targetRange: NSRange) -> NSRange {
let finalRange = listFormatter.removeAttributes(from: storage, at: targetRange)
liFormatter.removeAttributes(from: storage, at: targetRange)
return finalRange
}
// MARK: - Blockquote indent methods
private func indent(blockquote: Blockquote, increase: Bool = true) {
let formatter = BlockquoteFormatter(placeholderAttributes: typingAttributes, increaseDepth: true)
let targetRange = formatter.applicationRange(for: selectedRange, in: storage)
performUndoable(at: targetRange) {
let finalRange: NSRange
if increase {
finalRange = increaseIndent(quoteFormatter: formatter, targetRange: targetRange)
} else {
finalRange = decreaseIndent(quoteFormatter: formatter, targetRange: targetRange)
}
typingAttributes = textStorage.attributes(at: targetRange.location, effectiveRange: nil)
return finalRange
}
}
// MARK: Blockquote increase or decrease indentation
private func increaseIndent(quoteFormatter: BlockquoteFormatter, targetRange: NSRange) -> NSRange {
let finalRange = quoteFormatter.applyAttributes(to: storage, at: targetRange)
return finalRange
}
private func decreaseIndent(quoteFormatter: BlockquoteFormatter, targetRange: NSRange) -> NSRange {
let finalRange = quoteFormatter.removeAttributes(from: storage, at: targetRange)
return finalRange
}
// MARK: - Pasteboard Helpers
internal func storeInPasteboard(encoded data: Data, pasteboard: UIPasteboard = UIPasteboard.general) {
if pasteboard.numberOfItems > 0 {
pasteboard.items[0][NSAttributedString.pastesboardUTI] = data;
} else {
pasteboard.addItems([[NSAttributedString.pastesboardUTI: data]])
}
}
internal func storeInPasteboard(html: String, pasteboard: UIPasteboard = UIPasteboard.general) {
if pasteboard.numberOfItems > 0 {
pasteboard.items[0][kUTTypeHTML as String] = html;
} else {
pasteboard.addItems([[kUTTypeHTML as String: html]])
}
}
// MARK: - Intercept keyboard operations
open override func insertText(_ text: String) {
// For some reason the text view is allowing the attachment style to be set in
// typingAttributes. That's simply not acceptable.
//
// This was causing the following issue:
// https://github.com/wordpress-mobile/AztecEditor-iOS/issues/462
//
typingAttributes[.attachment] = nil
guard !ensureRemovalOfParagraphAttributesWhenPressingEnterInAnEmptyParagraph(input: text) else {
return
}
/// Whenever the user is at the end of the document, while editing a [List, Blockquote, Pre], we'll need
/// to insert a `\n` character, so that the Layout Manager immediately renders the List's new bullet
/// (or Blockquote's BG).
///
ensureInsertionOfEndOfLine(beforeInserting: text)
// Emoji Fix:
// Fallback to the default font, whenever the Active Font's Family doesn't match with the Default Font's family.
// We do this twice (before and after inserting text), in order to properly handle two scenarios:
//
// - Before: Corrects the typing attributes in the scenario in which the user moves the cursor around.
// Placing the caret after an emoji might update the typing attributes, and in some scenarios, the SDK might
// fallback to Courier New.
//
// - After: If the user enters an Emoji, toggling Bold / Italics breaks. This is due to a glitch in the
// SDK: the font "applied" after inserting an emoji breaks with our styling mechanism.
//
restoreDefaultFontIfNeeded()
ensureRemovalOfLinkTypingAttribute(at: selectedRange)
super.insertText(text)
evaluateRemovalOfSingleLineParagraphAttributesAfterSelectionChange()
restoreDefaultFontIfNeeded()
ensureCursorRedraw(afterEditing: text)
}
open override func deleteBackward() {
var deletionRange = selectedRange
var deletedString = NSAttributedString()
if deletionRange.length == 0 {
deletionRange.location = max(selectedRange.location - 1, 0)
deletionRange.length = 1
}
if storage.length > 0 {
deletedString = storage.attributedSubstring(from: deletionRange)
}
ensureRemovalOfParagraphStylesBeforeRemovingCharacter(at: selectedRange)
super.deleteBackward()
evaluateRemovalOfSingleLineParagraphAttributesAfterSelectionChange()
ensureRemovalOfParagraphAttributesWhenPressingBackspaceAndEmptyingTheDocument()
ensureCursorRedraw(afterEditing: deletedString.string)
recalculateTypingAttributes()
notifyTextViewDidChange()
}
// MARK: - UIView Overrides
open override func didMoveToWindow() {
super.didMoveToWindow()
layoutIfNeeded()
}
// MARK: - UITextView Overrides
open override func caretRect(for position: UITextPosition) -> CGRect {
var caretRect = super.caretRect(for: position)
let characterIndex = offset(from: beginningOfDocument, to: position)
guard layoutManager.isValidGlyphIndex(characterIndex) else {
return caretRect
}
let glyphIndex = layoutManager.glyphIndexForCharacter(at: characterIndex)
let usedLineFragment = layoutManager.lineFragmentUsedRect(forGlyphAt: glyphIndex, effectiveRange: nil)
guard !usedLineFragment.isEmpty else {
return caretRect
}
caretRect.origin.y = usedLineFragment.origin.y + textContainerInset.top
caretRect.size.height = usedLineFragment.size.height
return caretRect
}
// MARK: - HTML Interaction
/// Converts the current Attributed Text into a raw HTML String
///
/// - Returns: The HTML version of the current Attributed String.
///
public func getHTML(prettify: Bool = true) -> String {
return storage.getHTML(prettify: prettify)
}
/// Loads the specified HTML into the editor, and records a new undo step,
/// making sure the undo stack isn't reset
///
/// - Parameters:
/// - html: the HTML to load into the editor.
///
public func setHTMLUndoable(_ html: String) {
replace(storage.rangeOfEntireString, withHTML: html)
recalculateTypingAttributes()
}
/// Loads the specified HTML into the editor.
///
/// - Parameter html: The raw HTML we'd be editing.
///
public func setHTML(_ html: String) {
// NOTE: there's a bug in UIKit that causes the textView's font to be changed under certain
// conditions. We are assigning the default font here again to avoid that issue.
//
// More information about the bug here:
// https://github.com/wordpress-mobile/WordPress-Aztec-iOS/issues/58
//
font = defaultFont
storage.setHTML(html, defaultAttributes: defaultAttributes)
recalculateTypingAttributes()
notifyTextViewDidChange()
formattingDelegate?.textViewCommandToggledAStyle()
}
public func replace(_ range: NSRange, withHTML html: String) {
let string = storage.htmlConverter.attributedString(from: html, defaultAttributes: defaultAttributes)
let originalString = storage.attributedSubstring(from: range)
let finalRange = NSRange(location: range.location, length: string.length)
undoManager?.registerUndo(withTarget: self, handler: { [weak self] target in
self?.undoTextReplacement(of: originalString, finalRange: finalRange)
})
storage.replaceCharacters(in: range, with: string)
selectedRange = NSRange(location: finalRange.location + finalRange.length, length: 0)
}
// MARK: - Attachment Helpers
open func registerAttachmentImageProvider(_ provider: TextViewAttachmentImageProvider) {
textAttachmentImageProvider.append(provider)
}
// MARK: - Getting format identifiers
private static let formatterMap: [FormattingIdentifier: AttributeFormatter] = [
.bold: Configuration.defaultBoldFormatter,
.italic: ItalicFormatter(),
.underline: SpanUnderlineFormatter(),
.strikethrough: StrikethroughFormatter(),
.link: LinkFormatter(),
.orderedlist: TextListFormatter(style: .ordered),
.unorderedlist: TextListFormatter(style: .unordered),
.blockquote: BlockquoteFormatter(),
.header1: HeaderFormatter(headerLevel: .h1),
.header2: HeaderFormatter(headerLevel: .h2),
.header3: HeaderFormatter(headerLevel: .h3),
.header4: HeaderFormatter(headerLevel: .h4),
.header5: HeaderFormatter(headerLevel: .h5),
.header6: HeaderFormatter(headerLevel: .h6),
.p: HTMLParagraphFormatter(),
.code: CodeFormatter(),
.mark: MarkFormatter()
]
/// Get a list of format identifiers spanning the specified range as a String array.
///
/// - Parameter range: An NSRange to inspect.
///
/// - Returns: A list of identifiers.
///
open func formattingIdentifiersSpanningRange(_ range: NSRange) -> Set<FormattingIdentifier> {
guard storage.length != 0 else {
return formattingIdentifiersForTypingAttributes()
}
if range.length == 0 {
return formattingIdentifiersAtIndex(range.location)
}
var identifiers = Set<FormattingIdentifier>()
for (key, formatter) in type(of: self).formatterMap {
if formatter.present(in: storage, at: range) {
identifiers.insert(key)
}
}
return identifiers
}
/// Get a list of format identifiers at a specific index as a String array.
///
/// - Parameter range: The character index to inspect.
///
/// - Returns: A list of identifiers.
///
open func formattingIdentifiersAtIndex(_ index: Int) -> Set<FormattingIdentifier> {
guard storage.length != 0 else {
return []
}
let index = adjustedIndex(index)
var identifiers = Set<FormattingIdentifier>()
for (key, formatter) in type(of: self).formatterMap {
if formatter.present(in: storage, at: index) {
identifiers.insert(key)
}
}
return identifiers
}
/// Get a list of format identifiers of the Typing Attributes.
///
/// - Returns: A list of Formatting Identifiers.
///
open func formattingIdentifiersForTypingAttributes() -> Set<FormattingIdentifier> {
let activeAttributes = typingAttributes
var identifiers = Set<FormattingIdentifier>()
for (key, formatter) in type(of: self).formatterMap where formatter.present(in: activeAttributes) {
identifiers.insert(key)
}
return identifiers
}
// MARK: - UIResponderStandardEditActions
open override func toggleBoldface(_ sender: Any?) {
// We need to make sure our formatter is called. We can't go ahead with the default
// implementation.
//
toggleBold(range: selectedRange)
formattingDelegate?.textViewCommandToggledAStyle()
}
open override func toggleItalics(_ sender: Any?) {
// We need to make sure our formatter is called. We can't go ahead with the default
// implementation.
//
toggleItalic(range: selectedRange)
formattingDelegate?.textViewCommandToggledAStyle()
}
open override func toggleUnderline(_ sender: Any?) {
// We need to make sure our formatter is called. We can't go ahead with the default
// implementation.
//
toggleUnderline(range: selectedRange)
formattingDelegate?.textViewCommandToggledAStyle()
}
// MARK: - Formatting
func toggle(formatter: AttributeFormatter, atRange range: NSRange) {
let applicationRange = formatter.applicationRange(for: range, in: textStorage)
let originalString = storage.attributedSubstring(from: applicationRange)
undoManager?.registerUndo(withTarget: self, handler: { [weak self] target in
self?.undoTextReplacement(of: originalString, finalRange: applicationRange)
})
storage.toggle(formatter: formatter, at: range)
if applicationRange.length == 0 {
typingAttributes = formatter.toggle(in: typingAttributes)
} else {
// NOTE: We are making sure that the selectedRange location is inside the string
// The selected range can be out of the string when you are adding content to the end of the string.
// In those cases we check the atributes of the previous caracter
let location = max(0,min(selectedRange.location, textStorage.length-1))
typingAttributes = textStorage.attributes(at: location, effectiveRange: nil)
}
notifyTextViewDidChange()
}
func apply(formatter: AttributeFormatter, atRange range: NSRange, remove: Bool) {
let applicationRange = formatter.applicationRange(for: range, in: textStorage)
let originalString = storage.attributedSubstring(from: applicationRange)
undoManager?.registerUndo(withTarget: self, handler: { [weak self] target in
self?.undoTextReplacement(of: originalString, finalRange: applicationRange)
})
if remove {
formatter.removeAttributes(from: storage, at: applicationRange)
} else {
formatter.applyAttributes(to: storage, at: applicationRange)
}
if applicationRange.length == 0 {
typingAttributes = formatter.toggle(in: typingAttributes)
} else {
// NOTE: We are making sure that the selectedRange location is inside the string
// The selected range can be out of the string when you are adding content to the end of the string.
// In those cases we check the atributes of the previous caracter