-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathEditorDemoController.swift
1357 lines (1121 loc) · 54 KB
/
EditorDemoController.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 Aztec
import Foundation
import MobileCoreServices
import Photos
import UIKit
import WordPressEditor
class EditorDemoController: UIViewController {
fileprivate(set) lazy var formatBar: Aztec.FormatBar = {
return self.createToolbar()
}()
private var richTextView: TextView {
get {
return editorView.richTextView
}
}
private var htmlTextView: UITextView {
get {
return editorView.htmlTextView
}
}
fileprivate(set) lazy var mediaInserter: MediaInserter = {
return MediaInserter(textView: self.richTextView, attachmentTextAttributes: Constants.mediaMessageAttributes)
}()
fileprivate(set) lazy var textViewAttachmentDelegate: TextViewAttachmentDelegate = {
return TextViewAttachmentDelegateProvider(baseController: self, attachmentTextAttributes: Constants.mediaMessageAttributes)
}()
fileprivate(set) lazy var editorView: Aztec.EditorView = {
let defaultHTMLFont: UIFont
defaultHTMLFont = UIFontMetrics.default.scaledFont(for: Constants.defaultContentFont)
let editorView = Aztec.EditorView(
defaultFont: Constants.defaultContentFont,
defaultHTMLFont: defaultHTMLFont,
defaultParagraphStyle: .default,
defaultMissingImage: Constants.defaultMissingImage)
editorView.clipsToBounds = false
setupHTMLTextView(editorView.htmlTextView)
setupRichTextView(editorView.richTextView)
return editorView
}()
private func setupRichTextView(_ textView: TextView) {
if wordPressMode {
textView.load(WordPressPlugin())
}
let accessibilityLabel = NSLocalizedString("Rich Content", comment: "Post Rich content")
self.configureDefaultProperties(for: textView, accessibilityLabel: accessibilityLabel)
textView.delegate = self
textView.formattingDelegate = self
textView.textAttachmentDelegate = self.textViewAttachmentDelegate
textView.accessibilityIdentifier = "richContentView"
textView.clipsToBounds = false
textView.smartDashesType = .no
textView.smartQuotesType = .no
}
private func setupHTMLTextView(_ textView: UITextView) {
let accessibilityLabel = NSLocalizedString("HTML Content", comment: "Post HTML content")
self.configureDefaultProperties(htmlTextView: textView, accessibilityLabel: accessibilityLabel)
textView.isHidden = true
textView.delegate = self
textView.accessibilityIdentifier = "HTMLContentView"
textView.autocorrectionType = .no
textView.autocapitalizationType = .none
textView.clipsToBounds = false
textView.adjustsFontForContentSizeCategory = true
textView.smartDashesType = .no
textView.smartQuotesType = .no
}
fileprivate(set) lazy var titleTextView: UITextView = {
let textView = UITextView()
textView.accessibilityLabel = NSLocalizedString("Title", comment: "Post title")
textView.delegate = self
textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline)
textView.returnKeyType = .next
textView.textColor = .darkText
textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = .clear
textView.textAlignment = .natural
textView.isScrollEnabled = false
return textView
}()
/// Placeholder Label
///
fileprivate(set) lazy var titlePlaceholderLabel: UILabel = {
let placeholderText = NSLocalizedString("Enter title here", comment: "Post title placeholder")
let titlePlaceholderLabel = UILabel()
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.lightGray, .font: UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline)]
titlePlaceholderLabel.attributedText = NSAttributedString(string: placeholderText, attributes: attributes)
titlePlaceholderLabel.sizeToFit()
titlePlaceholderLabel.translatesAutoresizingMaskIntoConstraints = false
titlePlaceholderLabel.textAlignment = .natural
return titlePlaceholderLabel
}()
fileprivate var titleHeightConstraint: NSLayoutConstraint!
fileprivate var titleTopConstraint: NSLayoutConstraint!
fileprivate var titlePlaceholderTopConstraint: NSLayoutConstraint!
fileprivate var titlePlaceholderLeadingConstraint: NSLayoutConstraint!
fileprivate(set) lazy var separatorView: UIView = {
let separatorView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 1))
separatorView.backgroundColor = UIColor.darkText
separatorView.translatesAutoresizingMaskIntoConstraints = false
return separatorView
}()
let sampleHTML: String?
let wordPressMode: Bool
private lazy var optionsTablePresenter = OptionsTablePresenter(presentingViewController: self, presentingTextView: richTextView)
// MARK: - Lifecycle Methods
init(withSampleHTML sampleHTML: String? = nil, wordPressMode: Bool) {
self.sampleHTML = sampleHTML
self.wordPressMode = wordPressMode
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
sampleHTML = nil
wordPressMode = false
super.init(coder: aDecoder)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
MediaAttachment.defaultAppearance.progressColor = UIColor.blue
MediaAttachment.defaultAppearance.progressBackgroundColor = UIColor.lightGray
MediaAttachment.defaultAppearance.progressHeight = 2.0
MediaAttachment.defaultAppearance.overlayColor = UIColor(red: CGFloat(46.0/255.0), green: CGFloat(69.0/255.0), blue: CGFloat(83.0/255.0), alpha: 0.6)
// Uncomment to add a border
// MediaAttachment.defaultAppearance.overlayBorderWidth = 3.0
// MediaAttachment.defaultAppearance.overlayBorderColor = UIColor(red: CGFloat(0.0/255.0), green: CGFloat(135.0/255.0), blue: CGFloat(190.0/255.0), alpha: 0.8)
edgesForExtendedLayout = UIRectEdge()
navigationController?.navigationBar.isTranslucent = false
view.addSubview(editorView)
view.addSubview(titleTextView)
view.addSubview(titlePlaceholderLabel)
view.addSubview(separatorView)
editorView.richTextView.textContainer.lineFragmentPadding = 0
editorView.richTextView.listIndentStyle = .varied
// color setup
if #available(iOS 13.0, *) {
view.backgroundColor = UIColor.systemBackground
titleTextView.textColor = UIColor.label
editorView.htmlTextView.textColor = UIColor.label
editorView.richTextView.textColor = UIColor.label
editorView.richTextView.blockquoteBackgroundColor = UIColor.secondarySystemBackground
editorView.richTextView.preBackgroundColor = UIColor.secondarySystemBackground
editorView.richTextView.blockquoteBorderColors = [.secondarySystemFill, .systemTeal, .systemBlue]
var attributes = editorView.richTextView.linkTextAttributes
attributes?[.foregroundColor] = UIColor.link
} else {
view.backgroundColor = UIColor.white
}
//Don't allow scroll while the constraints are being setup and text set
editorView.isScrollEnabled = false
configureConstraints()
registerAttachmentImageProviders()
let html: String
if let sampleHTML = sampleHTML {
html = sampleHTML
} else {
html = ""
}
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(changeFont))
editorView.setHTML(html)
editorView.becomeFirstResponder()
}
@objc func changeFont() {
editorView.richTextView.defaultFont = UIFont.preferredFont(forTextStyle: .callout)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
nc.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Reanable scroll after setup is done
editorView.isScrollEnabled = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
let nc = NotificationCenter.default
nc.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
nc.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
optionsTablePresenter.dismiss()
}
// MARK: - Title and Title placeholder position methods
func updateTitlePosition() {
titleTopConstraint.constant = -(editorView.contentOffset.y + editorView.contentInset.top)
titlePlaceholderTopConstraint.constant = titleTextView.textContainerInset.top + titleTextView.contentInset.top
titlePlaceholderLeadingConstraint.constant = titleTextView.textContainerInset.left + titleTextView.contentInset.left + titleTextView.textContainer.lineFragmentPadding
var contentInset = editorView.contentInset
contentInset.top = titleHeightConstraint.constant + separatorView.frame.height
editorView.contentInset = contentInset
updateScrollInsets()
}
func updateScrollInsets() {
var scrollInsets = editorView.contentInset
var rightMargin = (view.frame.maxX - editorView.frame.maxX)
rightMargin -= view.safeAreaInsets.right
scrollInsets.right = -rightMargin
editorView.horizontalScrollIndicatorInsets = scrollInsets
}
func updateTitleHeight() {
let layoutMargins = view.layoutMargins
let insets = titleTextView.textContainerInset
var titleWidth = titleTextView.bounds.width
if titleWidth <= 0 {
// Use the title text field's width if available, otherwise calculate it.
titleWidth = view.frame.width - (insets.left + insets.right + layoutMargins.left + layoutMargins.right)
}
let sizeThatShouldFitTheContent = titleTextView.sizeThatFits(CGSize(width: titleWidth, height: CGFloat.greatestFiniteMagnitude))
titleHeightConstraint.constant = max(sizeThatShouldFitTheContent.height, titleTextView.font!.lineHeight + insets.top + insets.bottom)
titlePlaceholderLabel.isHidden = !titleTextView.text.isEmpty
var contentInset = editorView.contentInset
contentInset.top = (titleHeightConstraint.constant + separatorView.frame.height)
editorView.contentInset = contentInset
editorView.contentOffset = CGPoint(x: 0, y: -contentInset.top)
}
// MARK: - Configuration Methods
override func updateViewConstraints() {
updateTitlePosition()
updateTitleHeight()
super.updateViewConstraints()
}
private func configureConstraints() {
titleHeightConstraint = titleTextView.heightAnchor.constraint(equalToConstant: ceil(titleTextView.font!.lineHeight))
titleTopConstraint = titleTextView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0)
titlePlaceholderTopConstraint = titlePlaceholderLabel.topAnchor.constraint(equalTo: titleTextView.topAnchor, constant:0)
titlePlaceholderLeadingConstraint = titlePlaceholderLabel.leadingAnchor.constraint(equalTo: titleTextView.leadingAnchor, constant: 0)
updateTitlePosition()
updateTitleHeight()
let layoutGuide = view.readableContentGuide
NSLayoutConstraint.activate([
titleTextView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor, constant: 0),
titleTextView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor, constant: 0),
titleHeightConstraint,
titleTopConstraint
])
NSLayoutConstraint.activate([
titlePlaceholderLeadingConstraint,
titlePlaceholderLabel.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor, constant: 0),
titlePlaceholderTopConstraint
])
NSLayoutConstraint.activate([
separatorView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor, constant: 0),
separatorView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor, constant: 0),
separatorView.topAnchor.constraint(equalTo: titleTextView.bottomAnchor, constant: 0),
separatorView.heightAnchor.constraint(equalToConstant: separatorView.frame.height)
])
NSLayoutConstraint.activate([
editorView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor),
editorView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor),
editorView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
editorView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
])
}
private func configureDefaultProperties(for textView: TextView, accessibilityLabel: String) {
textView.accessibilityLabel = accessibilityLabel
textView.font = Constants.defaultContentFont
textView.keyboardDismissMode = .interactive
if #available(iOS 13.0, *) {
textView.textColor = UIColor.label
textView.defaultTextColor = UIColor.label
} else {
// Fallback on earlier versions
textView.textColor = UIColor(red: 0x1A/255.0, green: 0x1A/255.0, blue: 0x1A/255.0, alpha: 1)
textView.defaultTextColor = UIColor(red: 0x1A/255.0, green: 0x1A/255.0, blue: 0x1A/255.0, alpha: 1)
}
textView.linkTextAttributes = [.foregroundColor: UIColor(red: 0x01 / 255.0, green: 0x60 / 255.0, blue: 0x87 / 255.0, alpha: 1), NSAttributedString.Key.underlineStyle: NSNumber(value: NSUnderlineStyle.single.rawValue)]
}
private func configureDefaultProperties(htmlTextView textView: UITextView, accessibilityLabel: String) {
textView.accessibilityLabel = accessibilityLabel
textView.font = Constants.defaultContentFont
textView.keyboardDismissMode = .interactive
if #available(iOS 13.0, *) {
textView.textColor = UIColor.label
if let htmlStorage = textView.textStorage as? HTMLStorage {
htmlStorage.textColor = UIColor.label
}
} else {
// Fallback on earlier versions
textView.textColor = UIColor(red: 0x1A/255.0, green: 0x1A/255.0, blue: 0x1A/255.0, alpha: 1)
}
textView.linkTextAttributes = [.foregroundColor: UIColor(red: 0x01 / 255.0, green: 0x60 / 255.0, blue: 0x87 / 255.0, alpha: 1), NSAttributedString.Key.underlineStyle: NSNumber(value: NSUnderlineStyle.single.rawValue)]
}
private func registerAttachmentImageProviders() {
let providers: [TextViewAttachmentImageProvider] = [
GutenpackAttachmentRenderer(),
SpecialTagAttachmentRenderer(),
CommentAttachmentRenderer(font: Constants.defaultContentFont),
HTMLAttachmentRenderer(font: Constants.defaultHtmlFont),
]
for provider in providers {
richTextView.registerAttachmentImageProvider(provider)
}
}
// MARK: - Helpers
@IBAction func toggleEditingMode() {
formatBar.overflowToolbar(expand: true)
editorView.toggleEditingMode()
}
// MARK: - Options VC
private let formattingIdentifiersWithOptions: [FormattingIdentifier] = [.orderedlist, .unorderedlist, .p, .header1, .header2, .header3, .header4, .header5, .header6]
private func formattingIdentifierHasOptions(_ formattingIdentifier: FormattingIdentifier) -> Bool {
return formattingIdentifiersWithOptions.contains(formattingIdentifier)
}
// MARK: - Keyboard Handling
@objc func keyboardWillShow(_ notification: Notification) {
guard let userInfo = notification.userInfo as? [String: AnyObject],
let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
refreshInsets(forKeyboardFrame: keyboardFrame)
}
@objc func keyboardWillHide(_ notification: Notification) {
guard let userInfo = notification.userInfo as? [String: AnyObject],
let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
refreshInsets(forKeyboardFrame: keyboardFrame)
optionsTablePresenter.dismiss()
}
fileprivate func refreshInsets(forKeyboardFrame keyboardFrame: CGRect) {
// The reason why we're converting the keyboard coordinates instead of just using
// keyboardFrame.height, is that we need to make sure the insets take into account the
// possibility that there could be other views on top or below the text view.
// keyboardInset is basically the distance between the top of the keyboard
// and the bottom of the text view.
let localKeyboardOrigin = view.convert(keyboardFrame.origin, from: nil)
let keyboardInset = max(view.frame.height - localKeyboardOrigin.y, 0)
let contentInset = UIEdgeInsets(
top: editorView.contentInset.top,
left: 0,
bottom: keyboardInset,
right: 0)
editorView.contentInset = contentInset
updateScrollInsets()
}
func updateFormatBar() {
guard let toolbar = richTextView.inputAccessoryView as? Aztec.FormatBar else {
return
}
let identifiers: Set<FormattingIdentifier>
if richTextView.selectedRange.length > 0 {
identifiers = richTextView.formattingIdentifiersSpanningRange(richTextView.selectedRange)
} else {
identifiers = richTextView.formattingIdentifiersForTypingAttributes()
}
toolbar.selectItemsMatchingIdentifiers(identifiers.map({ $0.rawValue }))
}
override var keyCommands: [UIKeyCommand] {
if titleTextView.isFirstResponder {
return [
UIKeyCommand(input: "\t", modifierFlags: [], action: #selector(tabOnTitle))
]
}
if richTextView.isFirstResponder {
return [ UIKeyCommand(title: NSLocalizedString("Bold", comment: "Discoverability title for bold formatting keyboard shortcut."), action:#selector(toggleBold), input:"B", modifierFlags: .command, propertyList: nil, alternates: []),
UIKeyCommand(title:NSLocalizedString("Italic", comment: "Discoverability title for italic formatting keyboard shortcut."), action:#selector(toggleItalic), input:"I", modifierFlags: .command ),
UIKeyCommand(title: NSLocalizedString("Strikethrough", comment:"Discoverability title for strikethrough formatting keyboard shortcut."), action:#selector(toggleStrikethrough), input:"S", modifierFlags: [.command]),
UIKeyCommand(title: NSLocalizedString("Underline", comment:"Discoverability title for underline formatting keyboard shortcut."), action:#selector(EditorDemoController.toggleUnderline(_:)), input:"U", modifierFlags: .command ),
UIKeyCommand(title: NSLocalizedString("Block Quote", comment: "Discoverability title for block quote keyboard shortcut."), action: #selector(toggleBlockquote), input:"Q", modifierFlags:[.command,.alternate]),
UIKeyCommand(title: NSLocalizedString("Insert Link", comment: "Discoverability title for insert link keyboard shortcut."), action:#selector(toggleLink), input:"K", modifierFlags:.command),
UIKeyCommand(title: NSLocalizedString("Insert Media", comment: "Discoverability title for insert media keyboard shortcut."), action:#selector(showImagePicker), input:"M", modifierFlags:[.command,.alternate]),
UIKeyCommand(title:NSLocalizedString("Bullet List", comment: "Discoverability title for bullet list keyboard shortcut."), action:#selector(toggleUnorderedList), input:"U", modifierFlags:[.command, .alternate]),
UIKeyCommand(title:NSLocalizedString("Numbered List", comment:"Discoverability title for numbered list keyboard shortcut."), action:#selector(toggleOrderedList), input:"O", modifierFlags:[.command, .alternate]),
UIKeyCommand(title:NSLocalizedString("Toggle HTML Source ", comment: "Discoverability title for HTML keyboard shortcut."), action:#selector(toggleEditingMode), input:"H", modifierFlags:[.command, .shift])
]
} else if htmlTextView.isFirstResponder {
return [UIKeyCommand(title:NSLocalizedString("Toggle HTML Source ", comment: "Discoverability title for HTML keyboard shortcut."), action:#selector(toggleEditingMode), input:"H", modifierFlags:[.command, .shift])
]
}
return []
}
// MARK: - Sample Content
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if richTextView.resignFirstResponder() {
richTextView.becomeFirstResponder()
}
if htmlTextView.resignFirstResponder() {
htmlTextView.becomeFirstResponder()
}
if titleTextView.resignFirstResponder() {
titleTextView.becomeFirstResponder()
}
}
}
extension EditorDemoController : UITextViewDelegate {
func textViewDidChangeSelection(_ textView: UITextView) {
updateFormatBar()
changeRichTextInputView(to: nil)
}
func textViewDidChange(_ textView: UITextView) {
switch textView {
case richTextView:
updateFormatBar()
case titleTextView:
updateTitleHeight()
default:
break
}
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
switch textView {
case titleTextView:
formatBar.enabled = false
case richTextView:
formatBar.enabled = true
case htmlTextView:
formatBar.enabled = false
// Disable the bar, except for the source code button
let htmlButton = formatBar.items.first(where: { $0.identifier == FormattingIdentifier.sourcecode.rawValue })
htmlButton?.isEnabled = true
default: break
}
textView.inputAccessoryView = formatBar
return true
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return false
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
updateTitlePosition()
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return true
}
}
extension EditorDemoController : Aztec.TextViewFormattingDelegate {
func textViewCommandToggledAStyle() {
updateFormatBar()
}
}
extension EditorDemoController : UITextFieldDelegate {
}
extension EditorDemoController {
enum EditMode {
case richText
case html
mutating func toggle() {
switch self {
case .html:
self = .richText
case .richText:
self = .html
}
}
}
}
// MARK: - Format Bar Delegate
extension EditorDemoController : Aztec.FormatBarDelegate {
func formatBarTouchesBegan(_ formatBar: FormatBar) {
}
func formatBar(_ formatBar: FormatBar, didChangeOverflowState state: FormatBarOverflowState) {
switch state {
case .hidden:
print("Format bar collapsed")
case .visible:
print("Format bar expanded")
}
}
}
// MARK: - Format Bar Actions
extension EditorDemoController {
func handleAction(for barItem: FormatBarItem) {
guard let identifier = barItem.identifier,
let formattingIdentifier = FormattingIdentifier(rawValue: identifier) else {
return
}
if !formattingIdentifierHasOptions(formattingIdentifier) {
optionsTablePresenter.dismiss()
}
switch formattingIdentifier {
case .bold:
toggleBold()
case .italic:
toggleItalic()
case .underline:
toggleUnderline()
case .strikethrough:
toggleStrikethrough()
case .blockquote:
toggleBlockquote()
case .unorderedlist, .orderedlist:
toggleList(fromItem: barItem)
case .link:
toggleLink()
case .media:
break
case .sourcecode:
toggleEditingMode()
case .p, .header1, .header2, .header3, .header4, .header5, .header6:
toggleHeader(fromItem: barItem)
case .more:
insertMoreAttachment()
case .horizontalruler:
insertHorizontalRuler()
case .code:
toggleCode()
default:
break
}
updateFormatBar()
}
@objc func toggleBold() {
richTextView.toggleBold(range: richTextView.selectedRange)
}
@objc func toggleItalic() {
richTextView.toggleItalic(range: richTextView.selectedRange)
}
func toggleUnderline() {
richTextView.toggleUnderline(range: richTextView.selectedRange)
}
@objc func toggleStrikethrough() {
richTextView.toggleStrikethrough(range: richTextView.selectedRange)
}
@objc func toggleBlockquote() {
richTextView.toggleBlockquote(range: richTextView.selectedRange)
}
@objc func toggleCode() {
richTextView.toggleCode(range: richTextView.selectedRange)
}
func insertHorizontalRuler() {
richTextView.replaceWithHorizontalRuler(at: richTextView.selectedRange)
}
func toggleHeader(fromItem item: FormatBarItem) {
guard !optionsTablePresenter.isOnScreen() else {
optionsTablePresenter.dismiss()
return
}
let options = Constants.headers.map { headerType -> OptionsTableViewOption in
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: CGFloat(headerType.fontSize))
]
let title = NSAttributedString(string: headerType.description, attributes: attributes)
return OptionsTableViewOption(image: headerType.iconImage, title: title)
}
let selectedIndex = Constants.headers.firstIndex(of: headerLevelForSelectedText())
let optionsTableViewController = OptionsTableViewController(options: options)
optionsTableViewController.cellDeselectedTintColor = .gray
optionsTablePresenter.present(
optionsTableViewController,
fromBarItem: item,
selectedRowIndex: selectedIndex,
onSelect: { [weak self] selected in
guard let range = self?.richTextView.selectedRange else {
return
}
self?.richTextView.toggleHeader(Constants.headers[selected], range: range)
self?.optionsTablePresenter.dismiss()
})
}
func toggleList(fromItem item: FormatBarItem) {
guard !optionsTablePresenter.isOnScreen() else {
optionsTablePresenter.dismiss()
return
}
let options = Constants.lists.map { (listType) -> OptionsTableViewOption in
return OptionsTableViewOption(image: listType.iconImage, title: NSAttributedString(string: listType.description, attributes: [:]))
}
var index: Int? = nil
if let listType = listTypeForSelectedText() {
index = Constants.lists.firstIndex(of: listType)
}
let optionsTableViewController = OptionsTableViewController(options: options)
optionsTableViewController.cellDeselectedTintColor = .gray
optionsTablePresenter.present(
optionsTableViewController,
fromBarItem: item,
selectedRowIndex: index,
onSelect: { [weak self] selected in
guard let range = self?.richTextView.selectedRange else { return }
let listType = Constants.lists[selected]
switch listType {
case .unordered:
self?.richTextView.toggleUnorderedList(range: range)
case .ordered:
self?.richTextView.toggleOrderedList(range: range)
}
self?.optionsTablePresenter.dismiss()
})
}
@objc func toggleUnorderedList() {
richTextView.toggleUnorderedList(range: richTextView.selectedRange)
}
@objc func toggleOrderedList() {
richTextView.toggleOrderedList(range: richTextView.selectedRange)
}
func changeRichTextInputView(to: UIView?) {
if richTextView.inputView == to {
return
}
richTextView.inputView = to
richTextView.reloadInputViews()
}
func headerLevelForSelectedText() -> Header.HeaderType {
var identifiers = Set<FormattingIdentifier>()
if (richTextView.selectedRange.length > 0) {
identifiers = richTextView.formattingIdentifiersSpanningRange(richTextView.selectedRange)
} else {
identifiers = richTextView.formattingIdentifiersForTypingAttributes()
}
let mapping: [FormattingIdentifier: Header.HeaderType] = [
.header1 : .h1,
.header2 : .h2,
.header3 : .h3,
.header4 : .h4,
.header5 : .h5,
.header6 : .h6,
]
for (key,value) in mapping {
if identifiers.contains(key) {
return value
}
}
return .none
}
func listTypeForSelectedText() -> TextList.Style? {
var identifiers = Set<FormattingIdentifier>()
if (richTextView.selectedRange.length > 0) {
identifiers = richTextView.formattingIdentifiersSpanningRange(richTextView.selectedRange)
} else {
identifiers = richTextView.formattingIdentifiersForTypingAttributes()
}
let mapping: [FormattingIdentifier: TextList.Style] = [
.orderedlist : .ordered,
.unorderedlist : .unordered
]
for (key,value) in mapping {
if identifiers.contains(key) {
return value
}
}
return nil
}
@objc func toggleLink() {
var linkTitle = ""
var linkURL: URL? = nil
var linkRange = richTextView.selectedRange
// Let's check if the current range already has a link assigned to it.
if let expandedRange = richTextView.linkFullRange(forRange: richTextView.selectedRange) {
linkRange = expandedRange
linkURL = richTextView.linkURL(forRange: expandedRange)
}
let target = richTextView.linkTarget(forRange: richTextView.selectedRange)
linkTitle = richTextView.attributedText.attributedSubstring(from: linkRange).string
let allowTextEdit = !richTextView.attributedText.containsAttachments(in: linkRange)
showLinkDialog(forURL: linkURL, text: linkTitle, target: target, range: linkRange, allowTextEdit: allowTextEdit)
}
func insertMoreAttachment() {
richTextView.replace(richTextView.selectedRange, withComment: Constants.moreAttachmentText)
}
func showLinkDialog(forURL url: URL?, text: String?, target: String?, range: NSRange, allowTextEdit: Bool = true) {
let isInsertingNewLink = (url == nil)
var urlToUse = url
if isInsertingNewLink {
let pasteboard = UIPasteboard.general
if let pastedURL = pasteboard.value(forPasteboardType:String(kUTTypeURL)) as? URL {
urlToUse = pastedURL
}
}
let insertButtonTitle = isInsertingNewLink ? NSLocalizedString("Insert Link", comment:"Label action for inserting a link on the editor") : NSLocalizedString("Update Link", comment:"Label action for updating a link on the editor")
let removeButtonTitle = NSLocalizedString("Remove Link", comment:"Label action for removing a link from the editor");
let cancelButtonTitle = NSLocalizedString("Cancel", comment:"Cancel button")
let alertController = UIAlertController(title:insertButtonTitle,
message:nil,
preferredStyle:UIAlertController.Style.alert)
alertController.view.accessibilityIdentifier = "linkModal"
alertController.addTextField(configurationHandler: { [weak self]textField in
textField.clearButtonMode = UITextField.ViewMode.always;
textField.placeholder = NSLocalizedString("URL", comment:"URL text field placeholder");
textField.keyboardType = .URL
textField.textContentType = .URL
textField.text = urlToUse?.absoluteString
textField.addTarget(self,
action:#selector(EditorDemoController.alertTextFieldDidChange),
for:UIControl.Event.editingChanged)
textField.accessibilityIdentifier = "linkModalURL"
})
if allowTextEdit {
alertController.addTextField(configurationHandler: { textField in
textField.clearButtonMode = UITextField.ViewMode.always
textField.placeholder = NSLocalizedString("Link Text", comment:"Link text field placeholder")
textField.isSecureTextEntry = false
textField.autocapitalizationType = UITextAutocapitalizationType.sentences
textField.autocorrectionType = UITextAutocorrectionType.default
textField.spellCheckingType = UITextSpellCheckingType.default
textField.text = text;
textField.accessibilityIdentifier = "linkModalText"
})
}
alertController.addTextField(configurationHandler: { textField in
textField.clearButtonMode = UITextField.ViewMode.always
textField.placeholder = NSLocalizedString("Target", comment:"Link text field placeholder")
textField.isSecureTextEntry = false
textField.autocapitalizationType = UITextAutocapitalizationType.sentences
textField.autocorrectionType = UITextAutocorrectionType.default
textField.spellCheckingType = UITextSpellCheckingType.default
textField.text = target;
textField.accessibilityIdentifier = "linkModalTarget"
})
let insertAction = UIAlertAction(title:insertButtonTitle,
style:UIAlertAction.Style.default,
handler:{ [weak self]action in
self?.richTextView.becomeFirstResponder()
guard let textFields = alertController.textFields else {
return
}
let linkURLField = textFields[0]
let linkTextField = textFields[1]
let linkTargetField = textFields[2]
let linkURLString = linkURLField.text
var linkTitle = linkTextField.text
let target = linkTargetField.text
if linkTitle == nil || linkTitle!.isEmpty {
linkTitle = linkURLString
}
guard
let urlString = linkURLString,
let url = URL(string:urlString)
else {
return
}
if allowTextEdit {
if let title = linkTitle {
self?.richTextView.setLink(url, title: title, target: target, inRange: range)
}
} else {
self?.richTextView.setLink(url, target: target, inRange: range)
}
})
insertAction.accessibilityLabel = "insertLinkButton"
let removeAction = UIAlertAction(title:removeButtonTitle,
style:UIAlertAction.Style.destructive,
handler:{ [weak self] action in
self?.richTextView.becomeFirstResponder()
self?.richTextView.removeLink(inRange: range)
})
let cancelAction = UIAlertAction(title: cancelButtonTitle,
style:UIAlertAction.Style.cancel,
handler:{ [weak self]action in
self?.richTextView.becomeFirstResponder()
})
alertController.addAction(insertAction)
if !isInsertingNewLink {
alertController.addAction(removeAction)
}
alertController.addAction(cancelAction)
// Disabled until url is entered into field
if let text = alertController.textFields?.first?.text {
insertAction.isEnabled = !text.isEmpty
}
present(alertController, animated:true, completion:nil)
}
@objc func alertTextFieldDidChange(_ textField: UITextField) {
guard
let alertController = presentedViewController as? UIAlertController,
let urlFieldText = alertController.textFields?.first?.text,
let insertAction = alertController.actions.first
else {
return
}
insertAction.isEnabled = !urlFieldText.isEmpty
}
@objc func tabOnTitle() {
if editorView.becomeFirstResponder() {
editorView.selectedTextRange = editorView.htmlTextView.textRange(from: editorView.htmlTextView.endOfDocument, to: editorView.htmlTextView.endOfDocument)
}
}
@objc func showImagePicker() {
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary) ?? []
picker.delegate = self
picker.allowsEditing = false
picker.navigationBar.isTranslucent = false
picker.modalPresentationStyle = .currentContext
present(picker, animated: true, completion: nil)
}
// MARK: -
func makeToolbarButton(identifier: FormattingIdentifier) -> FormatBarItem {
let button = FormatBarItem(image: identifier.iconImage, identifier: identifier.rawValue)
button.accessibilityLabel = identifier.accessibilityLabel
button.accessibilityIdentifier = identifier.accessibilityIdentifier
return button
}
func createToolbar() -> Aztec.FormatBar {
let mediaItem = makeToolbarButton(identifier: .media)
let scrollableItems = scrollableItemsForToolbar
let overflowItems = overflowItemsForToolbar
let toolbar = Aztec.FormatBar()
if #available(iOS 13.0, *) {
toolbar.backgroundColor = UIColor.systemGroupedBackground
toolbar.tintColor = UIColor.secondaryLabel
toolbar.highlightedTintColor = UIColor.systemBlue
toolbar.selectedTintColor = UIColor.systemBlue
toolbar.disabledTintColor = .systemGray4
toolbar.dividerTintColor = UIColor.separator
} else {
toolbar.tintColor = .gray
toolbar.highlightedTintColor = .blue
toolbar.selectedTintColor = view.tintColor
toolbar.disabledTintColor = .lightGray
toolbar.dividerTintColor = .gray
}