-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
GutenbergViewController.swift
1207 lines (994 loc) · 46.9 KB
/
GutenbergViewController.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 WPMediaPicker
import Gutenberg
import Aztec
import WordPressFlux
import Kanvas
class GutenbergViewController: UIViewController, PostEditor {
let errorDomain: String = "GutenbergViewController.errorDomain"
enum RequestHTMLReason {
case publish
case close
case more
case switchToAztec
case switchBlog
case autoSave
}
private lazy var stockPhotos: GutenbergStockPhotos = {
return GutenbergStockPhotos(gutenberg: gutenberg, mediaInserter: mediaInserterHelper)
}()
private lazy var filesAppMediaPicker: GutenbergFilesAppMediaSource = {
return GutenbergFilesAppMediaSource(gutenberg: gutenberg, mediaInserter: mediaInserterHelper)
}()
private lazy var tenorMediaPicker: GutenbergTenorMediaPicker = {
return GutenbergTenorMediaPicker(gutenberg: gutenberg, mediaInserter: mediaInserterHelper)
}()
lazy var gutenbergSettings: GutenbergSettings = {
return GutenbergSettings()
}()
let ghostView = GutenGhostView()
private lazy var service: BlogJetpackSettingsService? = {
guard
let settings = post.blog.settings,
let context = settings.managedObjectContext
else {
return nil
}
return BlogJetpackSettingsService(managedObjectContext: context)
}()
// MARK: - Aztec
var replaceEditor: (EditorViewController, EditorViewController) -> ()
// MARK: - PostEditor
var html: String {
set {
post.content = newValue
}
get {
return post.content ?? ""
}
}
var postTitle: String {
set {
post.postTitle = newValue
}
get {
return post.postTitle ?? ""
}
}
/// Maintainer of state for editor - like for post button
///
private(set) lazy var postEditorStateContext: PostEditorStateContext = {
return PostEditorStateContext(post: post, delegate: self)
}()
var verificationPromptHelper: VerificationPromptHelper?
var analyticsEditorSource: String {
return Analytics.editorSource
}
var editorSession: PostEditorAnalyticsSession
var onClose: ((Bool, Bool) -> Void)?
var isOpenedDirectlyForPhotoPost: Bool = false
var postIsReblogged: Bool = false
// MARK: - Editor Media actions
var isUploadingMedia: Bool {
return mediaInserterHelper.isUploadingMedia()
}
var hasFailedMedia: Bool {
return mediaInserterHelper.hasFailedMedia()
}
func cancelUploadOfAllMedia(for post: AbstractPost) {
return mediaInserterHelper.cancelUploadOfAllMedia()
}
var mediaToInsertOnPost = [Media]()
func prepopulateMediaItems(_ media: [Media]) {
mediaToInsertOnPost = media
}
private func insertPrePopulatedMedia() {
for media in mediaToInsertOnPost {
guard
media.mediaType == .image, // just images for now
let mediaID = media.mediaID?.int32Value,
let mediaURLString = media.remoteURL,
let mediaURL = URL(string: mediaURLString) else {
continue
}
gutenberg.appendMedia(id: mediaID, url: mediaURL, type: .image)
}
mediaToInsertOnPost = []
}
private func showMediaSelectionOnStart() {
isOpenedDirectlyForPhotoPost = false
mediaPickerHelper.presentMediaPickerFullScreen(animated: true,
filter: .image,
dataSourceType: .device,
allowMultipleSelection: false,
callback: {(asset) in
guard let phAsset = asset as? [PHAsset] else {
return
}
self.mediaInserterHelper.insertFromDevice(assets: phAsset, callback: { media in
guard let media = media,
let mediaInfo = media.first,
let mediaID = mediaInfo.id,
let mediaURLString = mediaInfo.url,
let mediaURL = URL(string: mediaURLString) else {
return
}
self.gutenberg.appendMedia(id: mediaID, url: mediaURL, type: .image)
})
})
}
private func editMedia(with mediaUrl: URL, callback: @escaping MediaPickerDidPickMediaCallback) {
let image = GutenbergMediaEditorImage(url: mediaUrl, post: post)
let mediaEditor = WPMediaEditor(image)
mediaEditor.editingAlreadyPublishedImage = true
mediaEditor.edit(from: self,
onFinishEditing: { [weak self] images, actions in
guard let image = images.first?.editedImage else {
// If the image wasn't edited, do nothing
return
}
self?.mediaInserterHelper.insertFromImage(image: image, callback: callback, source: .mediaEditor)
})
}
private func confirmEditingGIF(with mediaUrl: URL, callback: @escaping MediaPickerDidPickMediaCallback) {
let alertController = UIAlertController(title: GIFAlertStrings.title,
message: GIFAlertStrings.message,
preferredStyle: .alert)
alertController.addCancelActionWithTitle(GIFAlertStrings.cancel)
alertController.addActionWithTitle(GIFAlertStrings.edit, style: .destructive) { _ in
self.editMedia(with: mediaUrl, callback: callback)
}
present(alertController, animated: true)
}
// MARK: - Set content
func setTitle(_ title: String) {
guard gutenberg.isLoaded else {
return
}
gutenberg.setTitle(title)
}
func setHTML(_ html: String) {
guard gutenberg.isLoaded else {
return
}
self.html = html
gutenberg.updateHtml(html)
}
func getHTML() -> String {
return html
}
var post: AbstractPost {
didSet {
removeObservers(fromPost: oldValue)
addObservers(toPost: post)
postEditorStateContext = PostEditorStateContext(post: post, delegate: self)
attachmentDelegate = AztecAttachmentDelegate(post: post)
mediaPickerHelper = GutenbergMediaPickerHelper(context: self, post: post)
mediaInserterHelper = GutenbergMediaInserterHelper(post: post, gutenberg: gutenberg)
stockPhotos = GutenbergStockPhotos(gutenberg: gutenberg, mediaInserter: mediaInserterHelper)
filesAppMediaPicker = GutenbergFilesAppMediaSource(gutenberg: gutenberg, mediaInserter: mediaInserterHelper)
tenorMediaPicker = GutenbergTenorMediaPicker(gutenberg: gutenberg, mediaInserter: mediaInserterHelper)
gutenbergImageLoader.post = post
refreshInterface()
}
}
/// If true, apply autosave content when the editor creates a revision.
///
var loadAutosaveRevision: Bool
let navigationBarManager = PostEditorNavigationBarManager()
lazy var attachmentDelegate = AztecAttachmentDelegate(post: post)
lazy var mediaPickerHelper: GutenbergMediaPickerHelper = {
return GutenbergMediaPickerHelper(context: self, post: post)
}()
lazy var mediaInserterHelper: GutenbergMediaInserterHelper = {
return GutenbergMediaInserterHelper(post: post, gutenberg: gutenberg)
}()
/// For autosaving - The debouncer will execute local saving every defined number of seconds.
/// In this case every 0.5 second
///
fileprivate(set) lazy var debouncer: Debouncer = {
return Debouncer(delay: PostEditorDebouncerConstants.autoSavingDelay, callback: debouncerCallback)
}()
lazy var autosaver = Autosaver { [weak self] in
self?.requestHTML(for: .autoSave)
}
var wordCount: UInt {
guard let currentMetrics = contentInfo else {
return 0
}
return UInt(currentMetrics.wordCount)
}
/// Media Library Data Source
///
lazy var mediaLibraryDataSource: MediaLibraryPickerDataSource = {
return MediaLibraryPickerDataSource(post: self.post)
}()
// MARK: - Private variables
private lazy var gutenbergImageLoader: GutenbergImageLoader = {
return GutenbergImageLoader(post: post)
}()
private lazy var gutenberg: Gutenberg = {
return Gutenberg(dataSource: self, extraModules: [gutenbergImageLoader])
}()
private var requestHTMLReason: RequestHTMLReason?
private(set) var mode: EditMode = .richText
private var analyticsEditor: PostEditorAnalyticsSession.Editor {
switch mode {
case .richText:
return .gutenberg
case .html:
return .html
}
}
private var isFirstGutenbergLayout = true
var shouldPresentInformativeDialog = false
lazy var shouldPresentPhase2informativeDialog: Bool = {
return gutenbergSettings.shouldPresentInformativeDialog(for: post.blog)
}()
private var themeSupportQuery: Receipt? = nil
private var themeSupportReceipt: Receipt? = nil
internal private(set) var contentInfo: ContentInfo?
// MARK: - Initializers
required init(
post: AbstractPost,
loadAutosaveRevision: Bool = false,
replaceEditor: @escaping (EditorViewController, EditorViewController) -> (),
editorSession: PostEditorAnalyticsSession? = nil) {
self.post = post
self.loadAutosaveRevision = loadAutosaveRevision
self.replaceEditor = replaceEditor
verificationPromptHelper = AztecVerificationPromptHelper(account: self.post.blog.account)
self.editorSession = editorSession ?? PostEditorAnalyticsSession(editor: .gutenberg, post: post)
super.init(nibName: nil, bundle: nil)
addObservers(toPost: post)
PostCoordinator.shared.cancelAnyPendingSaveOf(post: post)
navigationBarManager.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
deinit {
tearDownKeyboardObservers()
removeObservers(fromPost: post)
gutenberg.invalidate()
attachmentDelegate.cancelAllPendingMediaRequests()
}
// MARK: - Lifecycle methods
override func viewDidLoad() {
super.viewDidLoad()
setupKeyboardObservers()
WPFontManager.loadNotoFontFamily()
createRevisionOfPost(loadAutosaveRevision: loadAutosaveRevision)
setupGutenbergView()
configureNavigationBar()
refreshInterface()
gutenberg.delegate = self
fetchEditorTheme()
presentNewPageNoticeIfNeeded()
service?.syncJetpackSettingsForBlog(post.blog, success: { [weak self] in
self?.gutenberg.updateCapabilities()
}, failure: { (error) in
DDLogError("Error syncing JETPACK: \(String(describing: error))")
})
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
verificationPromptHelper?.updateVerificationStatus()
ghostView.startAnimation()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Handles refreshing controls with state context after options screen is dismissed
editorContentWasUpdated()
}
override func viewLayoutMarginsDidChange() {
super.viewLayoutMarginsDidChange()
ghostView.frame = view.frame
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
ghostView.frame = view.frame
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Required to work around an issue present in iOS 14 beta 2
// https://github.com/wordpress-mobile/WordPress-iOS/issues/14460
if #available(iOS 14.0, *),
presentedViewController?.view.accessibilityIdentifier == MoreSheetAlert.accessibilityIdentifier {
dismiss(animated: true)
}
}
// MARK: - Functions
private var keyboardShowObserver: Any?
private var keyboardHideObserver: Any?
private var keyboardFrame = CGRect.zero
private var suggestionViewBottomConstraint: NSLayoutConstraint?
private var previousFirstResponder: UIView?
private func setupKeyboardObservers() {
keyboardShowObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: .main) { [weak self] (notification) in
if let self = self, let keyboardRect = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
self.keyboardFrame = keyboardRect
self.updateConstraintsToAvoidKeyboard(frame: keyboardRect)
}
}
keyboardHideObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: .main) { [weak self] (notification) in
if let self = self, let keyboardRect = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
self.keyboardFrame = keyboardRect
self.updateConstraintsToAvoidKeyboard(frame: keyboardRect)
}
}
}
private func tearDownKeyboardObservers() {
if let keyboardShowObserver = keyboardShowObserver {
NotificationCenter.default.removeObserver(keyboardShowObserver)
}
if let keyboardHideObserver = keyboardHideObserver {
NotificationCenter.default.removeObserver(keyboardHideObserver)
}
}
private func configureNavigationBar() {
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.accessibilityIdentifier = "Gutenberg Editor Navigation Bar"
navigationItem.leftBarButtonItems = navigationBarManager.leftBarButtonItems
navigationItem.rightBarButtonItems = navigationBarManager.rightBarButtonItems
}
private func reloadBlogPickerButton() {
var pickerTitle = post.blog.url ?? String()
if let blogName = post.blog.settings?.name, blogName.isEmpty == false {
pickerTitle = blogName
}
navigationBarManager.reloadBlogPickerButton(with: pickerTitle, enabled: !isSingleSiteMode)
}
private func reloadEditorContents() {
let content = post.content ?? String()
setTitle(post.postTitle ?? "")
setHTML(content)
SiteSuggestionService.shared.prefetchSuggestions(for: self.post.blog) { [weak self] in
self?.gutenberg.updateCapabilities()
}
}
private func refreshInterface() {
reloadBlogPickerButton()
reloadEditorContents()
reloadPublishButton()
}
func contentByStrippingMediaAttachments() -> String {
return html //TODO: return media attachment stripped version in future
}
func toggleEditingMode() {
gutenberg.toggleHTMLMode()
mode.toggle()
editorSession.switch(editor: analyticsEditor)
}
func requestHTML(for reason: RequestHTMLReason) {
requestHTMLReason = reason
gutenberg.requestHTML()
}
func focusTitleIfNeeded() {
guard !post.hasContent(), shouldPresentInformativeDialog == false, shouldPresentPhase2informativeDialog == false else {
return
}
gutenberg.setFocusOnTitle()
}
private func presentNewPageNoticeIfNeeded() {
// Validate if the post is a newly created page or not.
guard post is Page,
post.isDraft(),
post.remoteStatus == AbstractPostRemoteStatus.local else { return }
let message = post.hasContent() ? NSLocalizedString("Page created", comment: "Notice that a page with content has been created") : NSLocalizedString("Blank page created", comment: "Notice that a page without content has been created")
gutenberg.showNotice(message)
}
private func handleMissingBlockAlertButtonPressed() {
let blog = post.blog
let JetpackSSOEnabled = (blog.jetpack?.isConnected ?? false) && (blog.settings?.jetpackSSOEnabled ?? false)
if JetpackSSOEnabled == false {
let controller = JetpackSettingsViewController(blog: blog)
controller.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(jetpackSettingsControllerDoneButtonPressed))
let navController = UINavigationController(rootViewController: controller)
present(navController, animated: true)
}
}
@objc private func jetpackSettingsControllerDoneButtonPressed() {
if presentedViewController != nil {
dismiss(animated: true) { [weak self] in
self?.gutenberg.updateCapabilities()
}
}
}
// MARK: - Event handlers
@objc func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return presentationController(forPresented: presented, presenting: presenting)
}
// MARK: - Switch to Aztec
func savePostEditsAndSwitchToAztec() {
requestHTML(for: .switchToAztec)
}
}
// MARK: - Views setup
extension GutenbergViewController {
private func setupGutenbergView() {
view.backgroundColor = .white
gutenberg.rootView.translatesAutoresizingMaskIntoConstraints = false
gutenberg.rootView.backgroundColor = .basicBackground
view.addSubview(gutenberg.rootView)
view.leftAnchor.constraint(equalTo: gutenberg.rootView.leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: gutenberg.rootView.rightAnchor).isActive = true
view.topAnchor.constraint(equalTo: gutenberg.rootView.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: gutenberg.rootView.bottomAnchor).isActive = true
}
}
// MARK: - GutenbergBridgeDelegate
extension GutenbergViewController: GutenbergBridgeDelegate {
func gutenbergDidRequestFetch(path: String, completion: @escaping (Result<Any, NSError>) -> Void) {
GutenbergNetworkRequest(path: path, blog: post.blog).request(completion: completion)
}
func editorDidAutosave() {
autosaver.contentDidChange()
}
func gutenbergDidRequestMedia(from source: Gutenberg.MediaSource, filter: [Gutenberg.MediaType], allowMultipleSelection: Bool, with callback: @escaping MediaPickerDidPickMediaCallback) {
let flags = mediaFilterFlags(using: filter)
switch source {
case .mediaLibrary:
gutenbergDidRequestMediaFromSiteMediaLibrary(filter: flags, allowMultipleSelection: allowMultipleSelection, with: callback)
case .deviceLibrary:
gutenbergDidRequestMediaFromDevicePicker(filter: flags, allowMultipleSelection: allowMultipleSelection, with: callback)
case .deviceCamera:
gutenbergDidRequestMediaFromCameraPicker(filter: flags, with: callback)
case .stockPhotos:
stockPhotos.presentPicker(origin: self, post: post, multipleSelection: allowMultipleSelection, callback: callback)
case .tenor:
tenorMediaPicker.presentPicker(origin: self,
post: post,
multipleSelection: allowMultipleSelection,
callback: callback)
case .otherApps, .allFiles:
filesAppMediaPicker.presentPicker(origin: self, filters: filter, allowedTypesOnBlog: post.blog.allowedTypeIdentifiers, multipleSelection: allowMultipleSelection, callback: callback)
default: break
}
}
func mediaFilterFlags(using filterArray: [Gutenberg.MediaType]) -> WPMediaType {
var mediaType: Int = 0
for filter in filterArray {
switch filter {
case .image:
mediaType = mediaType | WPMediaType.image.rawValue
case .video:
mediaType = mediaType | WPMediaType.video.rawValue
case .audio:
mediaType = mediaType | WPMediaType.audio.rawValue
case .other:
mediaType = mediaType | WPMediaType.other.rawValue
case .any:
mediaType = mediaType | WPMediaType.all.rawValue
}
}
return WPMediaType(rawValue: mediaType)
}
func gutenbergDidRequestMediaFromSiteMediaLibrary(filter: WPMediaType, allowMultipleSelection: Bool, with callback: @escaping MediaPickerDidPickMediaCallback) {
mediaPickerHelper.presentMediaPickerFullScreen(animated: true,
filter: filter,
dataSourceType: .mediaLibrary,
allowMultipleSelection: allowMultipleSelection,
callback: {(assets) in
guard let media = assets as? [Media] else {
callback(nil)
return
}
self.mediaInserterHelper.insertFromSiteMediaLibrary(media: media, callback: callback)
})
}
func gutenbergDidRequestMediaFromDevicePicker(filter: WPMediaType, allowMultipleSelection: Bool, with callback: @escaping MediaPickerDidPickMediaCallback) {
mediaPickerHelper.presentMediaPickerFullScreen(animated: true,
filter: filter,
dataSourceType: .device,
allowMultipleSelection: allowMultipleSelection,
callback: {(assets) in
guard let phAssets = assets as? [PHAsset] else {
callback(nil)
return
}
self.mediaInserterHelper.insertFromDevice(assets: phAssets, callback: callback)
})
}
func gutenbergDidRequestMediaFromCameraPicker(filter: WPMediaType, with callback: @escaping MediaPickerDidPickMediaCallback) {
mediaPickerHelper.presentCameraCaptureFullScreen(animated: true,
filter: filter,
callback: {(assets) in
guard let phAsset = assets?.first as? PHAsset else {
callback(nil)
return
}
self.mediaInserterHelper.insertFromDevice(asset: phAsset, callback: callback)
})
}
func gutenbergDidRequestMediaEditor(with mediaUrl: URL, callback: @escaping MediaPickerDidPickMediaCallback) {
guard !mediaUrl.isGif else {
confirmEditingGIF(with: mediaUrl, callback: callback)
return
}
editMedia(with: mediaUrl, callback: callback)
}
func gutenbergDidRequestImport(from url: URL, with callback: @escaping MediaImportCallback) {
mediaInserterHelper.insertFromDevice(url: url, callback: { media in
callback(media?.first)
})
}
func gutenbergDidRequestMediaUploadSync() {
self.mediaInserterHelper.syncUploads()
}
func gutenbergDidRequestMediaUploadCancelation(for mediaID: Int32) {
guard let media = mediaInserterHelper.mediaFor(uploadID: mediaID) else {
return
}
mediaInserterHelper.cancelUploadOf(media: media)
}
struct AnyEncodable: Encodable {
let value: Encodable
init(value: Encodable) {
self.value = value
}
func encode(to encoder: Encoder) throws {
try value.encode(to: encoder)
}
}
func gutenbergDidRequestMediaFilesEditorLoad(_ mediaFiles: [[String: Any]], blockId: String) {
let files = mediaFiles.compactMap({ content -> MediaFile? in
return MediaFile.file(from: content)
})
let controller = StoryEditor.editor(post: post, mediaFiles: files, publishOnCompletion: false, updated: { [weak self] result in
switch result {
case .success:
self?.dismiss(animated: true, completion: nil)
case .failure(let error):
self?.dismiss(animated: true, completion: nil)
let controller = UIAlertController(title: "Failed to create story", message: "Error: \(error)", preferredStyle: .alert)
let dismiss = UIAlertAction(title: "Dismiss", style: .default) { _ in
controller.dismiss(animated: true, completion: nil)
}
controller.addAction(dismiss)
self?.present(controller, animated: true, completion: nil)
}
}, uploaded: { [weak self] result in
switch result {
case .success(let post):
self?.setHTML(post.content ?? "")
case .failure(let error):
let controller = UIAlertController(title: "Failed to create story", message: "Error: \(error)", preferredStyle: .alert)
let dismiss = UIAlertAction(title: "Dismiss", style: .default) { _ in
controller.dismiss(animated: true, completion: nil)
}
controller.addAction(dismiss)
self?.present(controller, animated: true, completion: nil)
}
})
controller.populate(with: files, completion: { [weak self] result in
switch result {
case .success:
self?.present(controller, animated: true, completion: {})
case .failure(let error):
os_log(.error, "Failed to populate Kanvas controller %@", error.localizedDescription)
}
})
}
func gutenbergDidRequestMediaUploadActionDialog(for mediaID: Int32) {
guard let media = mediaInserterHelper.mediaFor(uploadID: mediaID) else {
return
}
let title: String = MediaAttachmentActionSheet.title
var message: String? = nil
let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
let dismissAction = UIAlertAction(title: MediaAttachmentActionSheet.dismissActionTitle, style: .cancel) { (action) in
}
alertController.addAction(dismissAction)
if media.remoteStatus == .pushing || media.remoteStatus == .processing {
let cancelUploadAction = UIAlertAction(title: MediaAttachmentActionSheet.stopUploadActionTitle, style: .destructive) { (action) in
self.mediaInserterHelper.cancelUploadOf(media: media)
}
alertController.addAction(cancelUploadAction)
} else if media.remoteStatus == .failed, let error = media.error {
message = error.localizedDescription
let retryUploadAction = UIAlertAction(title: MediaAttachmentActionSheet.retryUploadActionTitle, style: .default) { (action) in
self.mediaInserterHelper.retryUploadOf(media: media)
}
alertController.addAction(retryUploadAction)
}
alertController.title = title
alertController.message = message
alertController.popoverPresentationController?.sourceView = view
alertController.popoverPresentationController?.sourceRect = view.frame
alertController.popoverPresentationController?.permittedArrowDirections = .any
present(alertController, animated: true, completion: nil)
}
func showAlertForEmptyPostPublish() {
let title: String = (self.post is Page) ? EmptyPostActionSheet.titlePage : EmptyPostActionSheet.titlePost
let message: String = EmptyPostActionSheet.message
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
let dismissAction = UIAlertAction(title: MediaAttachmentActionSheet.dismissActionTitle, style: .cancel) { (action) in
}
alertController.addAction(dismissAction)
alertController.title = title
alertController.message = message
alertController.popoverPresentationController?.sourceView = view
alertController.popoverPresentationController?.sourceRect = view.frame
alertController.popoverPresentationController?.permittedArrowDirections = .any
present(alertController, animated: true, completion: nil)
}
func editorHasContent(title: String, content: String) -> Bool {
let hasTitle = !title.isEmpty
var hasContent = !content.isEmpty
if let contentInfo = contentInfo {
let isEmpty = contentInfo.blockCount == 0
let isOneEmptyParagraph = (contentInfo.blockCount == 1 && contentInfo.paragraphCount == 1 && contentInfo.characterCount == 0)
hasContent = !(isEmpty || isOneEmptyParagraph)
}
return hasTitle || hasContent
}
func gutenbergDidProvideHTML(title: String, html: String, changed: Bool, contentInfo: ContentInfo?) {
if changed {
self.html = html
self.postTitle = title
}
self.contentInfo = contentInfo
editorContentWasUpdated()
mapUIContentToPostAndSave(immediate: true)
if let reason = requestHTMLReason {
requestHTMLReason = nil // clear the reason
switch reason {
case .publish:
if editorHasContent(title: title, content: html) {
handlePublishButtonTap()
} else {
showAlertForEmptyPostPublish()
}
case .close:
cancelEditing()
case .more:
displayMoreSheet()
case .switchToAztec:
editorSession.switch(editor: .classic)
EditorFactory().switchToAztec(from: self)
case .switchBlog:
blogPickerWasPressed()
case .autoSave:
break
}
}
}
func gutenbergDidLayout() {
defer {
isFirstGutenbergLayout = false
}
if isFirstGutenbergLayout {
insertPrePopulatedMedia()
if isOpenedDirectlyForPhotoPost {
showMediaSelectionOnStart()
}
focusTitleIfNeeded()
mediaInserterHelper.refreshMediaStatus()
refreshEditorTheme()
}
}
func gutenbergDidMount(unsupportedBlockNames: [String]) {
if !editorSession.started {
// Note that this method is also used to track startup performance
// It assumes this is being called when the editor has finished loading
// If you need to refactor this, please ensure that the startup_time_ms property
// is still reflecting the actual startup time of the editor
editorSession.start(unsupportedBlocks: unsupportedBlockNames)
}
}
func gutenbergDidEmitLog(message: String, logLevel: LogLevel) {
switch logLevel {
case .trace:
DDLogDebug(message)
case .info:
DDLogInfo(message)
case .warn:
DDLogWarn(message)
case .error, .fatal:
DDLogError(message)
}
}
func gutenbergDidLogUserEvent(_ event: GutenbergUserEvent) {
switch event {
case .editorSessionTemplateApply(let template):
editorSession.apply(template: template)
case .editorSessionTemplatePreview(let template):
editorSession.preview(template: template)
}
}
func gutenbergDidRequestImagePreview(with fullSizeUrl: URL, thumbUrl: URL?) {
navigationController?.definesPresentationContext = true
let controller: WPImageViewController
if let image = AnimatedImageCache.shared.cachedStaticImage(url: fullSizeUrl) {
controller = WPImageViewController(image: image)
} else {
controller = WPImageViewController(externalMediaURL: fullSizeUrl)
}
controller.post = self.post
controller.modalTransitionStyle = .crossDissolve
controller.modalPresentationStyle = .overCurrentContext
self.present(controller, animated: true)
}
func gutenbergDidRequestUnsupportedBlockFallback(for block: Block) {
do {
let controller = try GutenbergWebNavigationController(with: post, block: block)
showGutenbergWeb(controller)
} catch {
DDLogError("Error loading Gutenberg Web with unsupported block: \(error)")
return showUnsupportedBlockUnexpectedErrorAlert()
}
}
func showGutenbergWeb(_ controller: GutenbergWebNavigationController) {
controller.onSave = { [weak self] newBlock in
self?.gutenberg.replace(block: newBlock)
}
present(controller, animated: true)
}
func showUnsupportedBlockUnexpectedErrorAlert() {
WPError.showAlert(
withTitle: NSLocalizedString("Error", comment: "Generic error alert title"),
message: NSLocalizedString("There has been an unexpected error.", comment: "Generic error alert message"),
withSupportButton: false
)
}
func updateConstraintsToAvoidKeyboard(frame: CGRect) {
keyboardFrame = frame
let minimumKeyboardHeight = CGFloat(50)
guard let suggestionViewBottomConstraint = suggestionViewBottomConstraint else {
return
}
// There are cases where the keyboard is not visible, but the system instead of returning zero, returns a low number, for example: 0, 3, 69.
// So in those scenarios, we just need to take in account the safe area and ignore the keyboard all together.
if keyboardFrame.height < minimumKeyboardHeight {
suggestionViewBottomConstraint.constant = -self.view.safeAreaInsets.bottom
}
else {
suggestionViewBottomConstraint.constant = -self.keyboardFrame.height
}
}
func gutenbergDidRequestMention(callback: @escaping (Swift.Result<String, NSError>) -> Void) {
DispatchQueue.main.async(execute: { [weak self] in
self?.showSuggestions(type: .mention, callback: callback)
})
}
func gutenbergDidRequestXpost(callback: @escaping (Swift.Result<String, NSError>) -> Void) {
DispatchQueue.main.async(execute: { [weak self] in
self?.showSuggestions(type: .xpost, callback: callback)
})
}
func gutenbergDidRequestFocalPointPickerTooltipShown() -> Bool {
return gutenbergSettings.focalPointPickerTooltipShown
}
func gutenbergDidRequestSetFocalPointPickerTooltipShown(_ tooltipShown: Bool) {
gutenbergSettings.focalPointPickerTooltipShown = tooltipShown
}
func gutenbergDidSendButtonPressedAction(_ buttonType: Gutenberg.ActionButtonType) {
switch buttonType {
case .missingBlockAlertActionButton:
handleMissingBlockAlertButtonPressed()
}
}
}
// MARK: - Suggestions implementation
extension GutenbergViewController {
private func showSuggestions(type: SuggestionType, callback: @escaping (Swift.Result<String, NSError>) -> Void) {
guard let siteID = post.blog.dotComID else {
callback(.failure(GutenbergSuggestionsViewController.SuggestionError.notAvailable as NSError))
return
}
switch type {
case .mention:
guard SuggestionService.shared.shouldShowSuggestions(for: post.blog) else { return }
case .xpost:
guard SiteSuggestionService.shared.shouldShowSuggestions(for: post.blog) else { return }
}
previousFirstResponder = view.findFirstResponder()
let suggestionsController = GutenbergSuggestionsViewController(siteID: siteID, suggestionType: type)
suggestionsController.onCompletion = { (result) in
callback(result)
suggestionsController.view.removeFromSuperview()
suggestionsController.removeFromParent()
if let previousFirstResponder = self.previousFirstResponder {
previousFirstResponder.becomeFirstResponder()
}
var analyticsName: String
switch type {
case .mention:
analyticsName = "user"
case .xpost:
analyticsName = "xpost"
}
var didSelectSuggestion = false
if case .success = result {
didSelectSuggestion = true
}
let analyticsProperties: [String: Any] = [
"suggestion_type": analyticsName,
"did_select_suggestion": didSelectSuggestion
]
WPAnalytics.track(.gutenbergSuggestionSessionFinished, properties: analyticsProperties)
}
addChild(suggestionsController)
view.addSubview(suggestionsController.view)
let suggestionsBottomConstraint = suggestionsController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
NSLayoutConstraint.activate([
suggestionsController.view.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor, constant: 0),
suggestionsController.view.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor, constant: 0),
suggestionsBottomConstraint,
suggestionsController.view.topAnchor.constraint(equalTo: view.safeTopAnchor)
])
self.suggestionViewBottomConstraint = suggestionsBottomConstraint
updateConstraintsToAvoidKeyboard(frame: keyboardFrame)
suggestionsController.didMove(toParent: self)
}
}
// MARK: - GutenbergBridgeDataSource
extension GutenbergViewController: GutenbergBridgeDataSource {
var isPreview: Bool {
return false
}