-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ThemeBrowserViewController.swift
988 lines (798 loc) · 38.1 KB
/
ThemeBrowserViewController.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
import Foundation
import CocoaLumberjack
import WordPressShared.WPAnalytics
import WordPressShared.WPStyleGuide
/**
* @brief Support for filtering themes by purchasability
* @details Currently purchasing themes via native apps is unsupported
*/
public enum ThemeType {
case all
case free
case premium
static let mayPurchase = false
static let types = [all, free, premium]
var title: String {
switch self {
case .all:
return NSLocalizedString("All", comment: "Browse all themes selection title")
case .free:
return NSLocalizedString("Free", comment: "Browse free themes selection title")
case .premium:
return NSLocalizedString("Premium", comment: "Browse premium themes selection title")
}
}
var predicate: NSPredicate? {
switch self {
case .all:
return nil
case .free:
return NSPredicate(format: "premium == 0")
case .premium:
return NSPredicate(format: "premium == 1")
}
}
}
/**
* @brief Publicly exposed theme interaction support
* @details Held as weak reference by owned subviews
*/
public protocol ThemePresenter: AnyObject {
var filterType: ThemeType { get set }
var screenshotWidth: Int { get }
func currentTheme() -> Theme?
func activateTheme(_ theme: Theme?)
func presentCustomizeForTheme(_ theme: Theme?)
func presentPreviewForTheme(_ theme: Theme?)
func presentDetailsForTheme(_ theme: Theme?)
func presentSupportForTheme(_ theme: Theme?)
func presentViewForTheme(_ theme: Theme?)
}
/// Invalidates the layout whenever the collection view's bounds change
@objc open class ThemeBrowserCollectionViewLayout: UICollectionViewFlowLayout {
open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return shouldInvalidateForNewBounds(newBounds)
}
open override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewFlowLayoutInvalidationContext {
let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext
context.invalidateFlowLayoutDelegateMetrics = shouldInvalidateForNewBounds(newBounds)
return context
}
fileprivate func shouldInvalidateForNewBounds(_ newBounds: CGRect) -> Bool {
guard let collectionView = collectionView else { return false }
return (newBounds.width != collectionView.bounds.width || newBounds.height != collectionView.bounds.height)
}
}
@objc open class ThemeBrowserViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, NSFetchedResultsControllerDelegate, UISearchControllerDelegate, UISearchResultsUpdating, ThemePresenter, WPContentSyncHelperDelegate {
// MARK: - Constants
@objc static let reuseIdentifierForThemesHeader = "ThemeBrowserSectionHeaderViewThemes"
@objc static let reuseIdentifierForCustomThemesHeader = "ThemeBrowserSectionHeaderViewCustomThemes"
static let themesLoaderFrame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 20.0)
// MARK: - Properties: must be set by parent
/**
* @brief The blog this VC will work with.
* @details Must be set by the creator of this VC.
*/
@objc open var blog: Blog!
// MARK: - Properties
@IBOutlet weak var collectionView: UICollectionView!
// swiftlint:disable:next weak_delegate
fileprivate lazy var customizerNavigationDelegate: ThemeWebNavigationDelegate = {
return ThemeWebNavigationDelegate()
}()
/**
* @brief The FRCs this VC will use to display filtered content.
*/
fileprivate lazy var themesController: NSFetchedResultsController<NSFetchRequestResult> = {
return self.createThemesFetchedResultsController()
}()
fileprivate lazy var customThemesController: NSFetchedResultsController<NSFetchRequestResult> = {
return self.createThemesFetchedResultsController()
}()
fileprivate func createThemesFetchedResultsController() -> NSFetchedResultsController<NSFetchRequestResult> {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Theme.entityName())
fetchRequest.fetchBatchSize = 20
let sort = NSSortDescriptor(key: "order", ascending: true)
fetchRequest.sortDescriptors = [sort]
let frc = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: self.themeService.coreDataStack.mainContext,
sectionNameKeyPath: nil,
cacheName: nil)
frc.delegate = self
return frc
}
fileprivate var themeCount: NSInteger {
return themesController.fetchedObjects?.count ?? 0
}
fileprivate var customThemeCount: NSInteger {
return blog.supports(BlogFeature.customThemes) ? (customThemesController.fetchedObjects?.count ?? 0) : 0
}
// Absolute count of available themes for the site, as it comes from the ThemeService
fileprivate var totalThemeCount: NSInteger = 0 {
didSet {
themesHeader?.themeCount = totalThemeCount
}
}
fileprivate var totalCustomThemeCount: NSInteger = 0 {
didSet {
customThemesHeader?.themeCount = totalCustomThemeCount
}
}
fileprivate var themesHeader: ThemeBrowserSectionHeaderView? {
didSet {
themesHeader?.descriptionLabel.text = NSLocalizedString("WordPress.com Themes",
comment: "Title for the WordPress.com themes section, should be the same as in Calypso").localizedUppercase
themesHeader?.themeCount = totalThemeCount > 0 ? totalThemeCount : themeCount
}
}
fileprivate var customThemesHeader: ThemeBrowserSectionHeaderView? {
didSet {
customThemesHeader?.descriptionLabel.text = NSLocalizedString("Uploaded themes",
comment: "Title for the user uploaded themes section, should be the same as in Calypso").localizedUppercase
customThemesHeader?.themeCount = totalCustomThemeCount > 0 ? totalCustomThemeCount : customThemeCount
}
}
fileprivate var hideSectionHeaders: Bool = false
fileprivate var searchController: UISearchController!
fileprivate var searchName = "" {
didSet {
if searchName != oldValue {
fetchThemes()
reloadThemes()
}
}
}
fileprivate var suspendedSearch = ""
@objc func resumingSearch() -> Bool {
return !suspendedSearch.trim().isEmpty
}
fileprivate var activityIndicator: UIActivityIndicatorView = {
let indicatorView = UIActivityIndicatorView(style: .medium)
indicatorView.frame = themesLoaderFrame
//TODO update color with white headers
indicatorView.color = .white
indicatorView.startAnimating()
return indicatorView
}()
open var filterType: ThemeType = ThemeType.mayPurchase ? .all : .free
/**
* @brief Collection view support
*/
fileprivate enum Section {
case search
case info
case customThemes
case themes
}
fileprivate var sections: [Section]!
fileprivate func reloadThemes() {
collectionView?.reloadData()
updateResults()
}
fileprivate func themeAtIndexPath(_ indexPath: IndexPath) -> Theme? {
if sections[indexPath.section] == .themes {
return themesController.object(at: IndexPath(row: indexPath.row, section: 0)) as? Theme
} else if sections[indexPath.section] == .customThemes {
return customThemesController.object(at: IndexPath(row: indexPath.row, section: 0)) as? Theme
}
return nil
}
fileprivate func updateActivateButton(isLoading: Bool) {
if isLoading {
activateButton?.customView = activityIndicator
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
activateButton?.customView = nil
activateButton?.isEnabled = false
activateButton?.title = ThemeAction.active.title
}
}
fileprivate var presentingTheme: Theme?
private var noResultsViewController: NoResultsViewController?
private struct NoResultsTitles {
static let noThemes = NSLocalizedString("No themes matching your search", comment: "Text displayed when theme name search has no matches")
static let fetchingThemes = NSLocalizedString("Fetching Themes...", comment: "Text displayed while fetching themes")
}
private var noResultsShown: Bool {
return noResultsViewController?.parent != nil
}
/**
* @brief Load theme screenshots at maximum displayed width
*/
@objc open var screenshotWidth: Int = {
guard let window = UIApplication.shared.mainWindow else {
assertionFailure("The mainWindow is not set")
return Int(Styles.imageWidthForFrameWidth(852))
}
let windowSize = window.bounds.size
let vWidth = Styles.imageWidthForFrameWidth(windowSize.width)
let hWidth = Styles.imageWidthForFrameWidth(windowSize.height)
let maxWidth = Int(max(hWidth, vWidth))
return maxWidth
}()
/**
* @brief The themes service we'll use in this VC and its helpers
*/
fileprivate let themeService = ThemeService(coreDataStack: ContextManager.sharedInstance())
fileprivate var themesSyncHelper: WPContentSyncHelper!
fileprivate var themesSyncingPage = 0
fileprivate var customThemesSyncHelper: WPContentSyncHelper!
fileprivate let syncPadding = 5
fileprivate var activateButton: UIBarButtonItem?
// MARK: - Private Aliases
fileprivate typealias Styles = WPStyleGuide.Themes
/**
* @brief Convenience method for browser instantiation
*
* @param blog The blog to browse themes for
*
* @returns ThemeBrowserViewController instance
*/
@objc open class func browserWithBlog(_ blog: Blog) -> ThemeBrowserViewController {
let storyboard = UIStoryboard(name: "ThemeBrowser", bundle: nil)
let viewController = storyboard.instantiateInitialViewController() as! ThemeBrowserViewController
viewController.blog = blog
return viewController
}
// MARK: - UIViewController
open override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
title = NSLocalizedString("Themes", comment: "Title of Themes browser page")
WPStyleGuide.configureColors(view: view, collectionView: collectionView)
fetchThemes()
sections = (themeCount == 0 && customThemeCount == 0) ? [.search, .customThemes, .themes] :
[.search, .info, .customThemes, .themes]
configureSearchController()
updateActiveTheme()
setupThemesSyncHelper()
if blog.supports(BlogFeature.customThemes) {
setupCustomThemesSyncHelper()
}
syncContent()
}
fileprivate func configureSearchController() {
extendedLayoutIncludesOpaqueBars = true
definesPresentationContext = true
searchController = UISearchController(searchResultsController: nil)
searchController.obscuresBackgroundDuringPresentation = false
searchController.delegate = self
searchController.searchResultsUpdater = self
collectionView.register(ThemeBrowserSearchHeaderView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: ThemeBrowserSearchHeaderView.reuseIdentifier)
collectionView.register(UINib(nibName: "ThemeBrowserSectionHeaderView", bundle: Bundle(for: ThemeBrowserSectionHeaderView.self)),
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForThemesHeader)
collectionView.register(UINib(nibName: "ThemeBrowserSectionHeaderView", bundle: Bundle(for: ThemeBrowserSectionHeaderView.self)),
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForCustomThemesHeader)
WPStyleGuide.configureSearchBar(searchController.searchBar)
}
fileprivate var searchBarHeight: CGFloat {
return searchController.searchBar.bounds.height + view.safeAreaInsets.top
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
collectionView?.collectionViewLayout.invalidateLayout()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerForKeyboardNotifications()
if resumingSearch() {
beginSearchFor(suspendedSearch)
suspendedSearch = ""
}
guard let theme = presentingTheme else {
return
}
presentingTheme = nil
if !theme.isCurrentTheme() {
// presented page may have activated this theme
updateActiveTheme()
}
}
open override func viewWillDisappear(_ animated: Bool) {
if searchController.isActive {
searchController.isActive = false
}
super.viewWillDisappear(animated)
unregisterForKeyboardNotifications()
}
fileprivate func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(ThemeBrowserViewController.keyboardDidShow(_:)),
name: UIResponder.keyboardDidShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(ThemeBrowserViewController.keyboardWillHide(_:)),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
fileprivate func unregisterForKeyboardNotifications() {
NotificationCenter.default.removeObserver(self,
name: UIResponder.keyboardDidShowNotification,
object: nil)
NotificationCenter.default.removeObserver(self,
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
@objc open func keyboardDidShow(_ notification: Foundation.Notification) {
let keyboardFrame = localKeyboardFrameFromNotification(notification)
let keyboardHeight = collectionView.frame.maxY - keyboardFrame.origin.y
collectionView.contentInset.bottom = keyboardHeight
collectionView.verticalScrollIndicatorInsets.top = searchBarHeight
collectionView.verticalScrollIndicatorInsets.bottom = keyboardHeight
}
@objc open func keyboardWillHide(_ notification: Foundation.Notification) {
let tabBarHeight = tabBarController?.tabBar.bounds.height ?? 0
collectionView.contentInset.top = view.safeAreaInsets.top
collectionView.contentInset.bottom = tabBarHeight
collectionView.verticalScrollIndicatorInsets.top = searchBarHeight
collectionView.verticalScrollIndicatorInsets.bottom = tabBarHeight
}
fileprivate func localKeyboardFrameFromNotification(_ notification: Foundation.Notification) -> CGRect {
let key = UIResponder.keyboardFrameEndUserInfoKey
guard let keyboardFrame = (notification.userInfo?[key] as? NSValue)?.cgRectValue else {
return .zero
}
// Convert the frame from window coordinates
return view.convert(keyboardFrame, from: nil)
}
// MARK: - Syncing the list of themes
fileprivate func updateActiveTheme() {
let lastActiveThemeId = blog.currentThemeId
_ = themeService.getActiveTheme(for: blog,
success: { [weak self] (theme: Theme?) in
if lastActiveThemeId != theme?.themeId {
self?.collectionView?.collectionViewLayout.invalidateLayout()
}
},
failure: { (error) in
DDLogError("Error updating active theme: \(String(describing: error?.localizedDescription))")
})
}
fileprivate func setupThemesSyncHelper() {
themesSyncHelper = WPContentSyncHelper()
themesSyncHelper.delegate = self
}
fileprivate func setupCustomThemesSyncHelper() {
customThemesSyncHelper = WPContentSyncHelper()
customThemesSyncHelper.delegate = self
}
fileprivate func syncContent() {
if themesSyncHelper.syncContent() &&
(!blog.supports(BlogFeature.customThemes) ||
customThemesSyncHelper.syncContent()) {
updateResults()
}
}
fileprivate func syncMoreThemesIfNeeded(_ indexPath: IndexPath) {
let paddedCount = indexPath.row + syncPadding
if paddedCount >= themeCount && themesSyncHelper.hasMoreContent && themesSyncHelper.syncMoreContent() {
updateResults()
}
}
fileprivate func syncThemePage(_ page: NSInteger, success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) {
assert(page > 0)
themesSyncingPage = page
_ = themeService.getThemesFor(blog,
page: themesSyncingPage,
sync: page == 1,
success: {[weak self](themes: [Theme]?, hasMore: Bool, themeCount: NSInteger) in
if let success = success {
success(hasMore)
}
self?.totalThemeCount = themeCount
},
failure: { (error) in
DDLogError("Error syncing themes: \(String(describing: error?.localizedDescription))")
if let failure = failure,
let error = error {
failure(error as NSError)
}
})
}
fileprivate func syncCustomThemes(success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) {
_ = themeService.getCustomThemes(for: blog,
sync: true,
success: {[weak self](themes: [Theme]?, hasMore: Bool, themeCount: NSInteger) in
if let success = success {
success(hasMore)
}
self?.totalCustomThemeCount = themeCount
},
failure: { (error) in
DDLogError("Error syncing themes: \(String(describing: error?.localizedDescription))")
if let failure = failure,
let error = error {
failure(error as NSError)
}
})
}
@objc open func currentTheme() -> Theme? {
guard let themeId = blog.currentThemeId, !themeId.isEmpty else {
return nil
}
for theme in blog.themes as! Set<Theme> {
if theme.themeId == themeId {
return theme
}
}
return nil
}
// MARK: - WPContentSyncHelperDelegate
func syncHelper(_ syncHelper: WPContentSyncHelper, syncContentWithUserInteraction userInteraction: Bool, success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) {
if syncHelper == themesSyncHelper {
syncThemePage(1, success: success, failure: failure)
} else if syncHelper == customThemesSyncHelper {
syncCustomThemes(success: success, failure: failure)
}
}
func syncHelper(_ syncHelper: WPContentSyncHelper, syncMoreWithSuccess success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) {
if syncHelper == themesSyncHelper {
let nextPage = themesSyncingPage + 1
syncThemePage(nextPage, success: success, failure: failure)
}
}
func syncContentEnded(_ syncHelper: WPContentSyncHelper) {
updateResults()
let lastVisibleTheme = collectionView?.indexPathsForVisibleItems.last ?? IndexPath(item: 0, section: 0)
if syncHelper == themesSyncHelper {
syncMoreThemesIfNeeded(lastVisibleTheme)
}
}
func hasNoMoreContent(_ syncHelper: WPContentSyncHelper) {
if syncHelper == themesSyncHelper {
themesSyncingPage = 0
}
collectionView?.collectionViewLayout.invalidateLayout()
}
// MARK: - UICollectionViewDataSource
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch sections[section] {
case .search, .info:
return 0
case .customThemes:
return customThemeCount
case .themes:
return themeCount
}
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ThemeBrowserCell.reuseIdentifier, for: indexPath) as! ThemeBrowserCell
cell.presenter = self
cell.theme = themeAtIndexPath(indexPath)
if sections[indexPath.section] == .themes {
syncMoreThemesIfNeeded(indexPath)
}
return cell
}
open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
if sections[indexPath.section] == .search {
let searchHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserSearchHeaderView.reuseIdentifier, for: indexPath) as! ThemeBrowserSearchHeaderView
searchHeader.searchBar = searchController.searchBar
return searchHeader
} else if sections[indexPath.section] == .info {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserHeaderView.reuseIdentifier, for: indexPath) as! ThemeBrowserHeaderView
header.presenter = self
return header
} else {
// We don't want the collectionView to reuse the section headers
// since we need to keep a reference to them to update the counts
if sections[indexPath.section] == .customThemes {
customThemesHeader = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForCustomThemesHeader, for: indexPath) as! ThemeBrowserSectionHeaderView)
customThemesHeader?.isHidden = customThemeCount == 0
return customThemesHeader!
} else {
themesHeader = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForCustomThemesHeader, for: indexPath) as! ThemeBrowserSectionHeaderView)
themesHeader?.isHidden = themeCount == 0
return themesHeader!
}
}
case UICollectionView.elementKindSectionFooter:
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "ThemeBrowserFooterView", for: indexPath)
return footer
default:
fatalError("Unexpected theme browser element")
}
}
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return sections.count
}
// MARK: - UICollectionViewDelegate
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let theme = themeAtIndexPath(indexPath) {
if theme.isCurrentTheme() {
presentCustomizeForTheme(theme)
} else {
theme.custom ? presentDetailsForTheme(theme) : presentViewForTheme(theme)
}
}
}
// MARK: - UICollectionViewDelegateFlowLayout
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: NSInteger) -> CGSize {
switch sections[section] {
case .themes, .customThemes:
if !hideSectionHeaders
&& blog.supports(BlogFeature.customThemes) {
return CGSize(width: 0, height: ThemeBrowserSectionHeaderView.height)
}
return .zero
case .search:
return CGSize(width: 0, height: searchController.searchBar.bounds.height)
case .info:
let horizontallyCompact = traitCollection.horizontalSizeClass == .compact
let height = Styles.headerHeight(horizontallyCompact, includingSearchBar: ThemeType.mayPurchase)
return CGSize(width: 0, height: height)
}
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let parentViewWidth = collectionView.frame.size.width
return Styles.cellSizeForFrameWidth(parentViewWidth)
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
guard sections[section] == .themes && themesSyncHelper.isLoadingMore else {
return CGSize.zero
}
return CGSize(width: 0, height: Styles.footerHeight)
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
switch sections[section] {
case .customThemes:
if !blog.supports(BlogFeature.customThemes) {
return .zero
}
return Styles.themeMargins
case .themes:
return Styles.themeMargins
case .info, .search:
return Styles.infoMargins
}
}
// MARK: - Search support
fileprivate func beginSearchFor(_ pattern: String) {
searchController.isActive = true
searchController.searchBar.text = pattern
searchName = pattern
}
// MARK: - UISearchControllerDelegate
open func willPresentSearchController(_ searchController: UISearchController) {
hideSectionHeaders = true
if sections[1] == .info {
collectionView?.collectionViewLayout.invalidateLayout()
setInfoSectionHidden(true)
}
}
open func didPresentSearchController(_ searchController: UISearchController) {
WPAppAnalytics.track(.themesAccessedSearch, with: blog)
}
open func willDismissSearchController(_ searchController: UISearchController) {
hideSectionHeaders = false
searchName = ""
searchController.searchBar.text = ""
}
open func didDismissSearchController(_ searchController: UISearchController) {
if sections[1] == .themes || sections[1] == .customThemes {
setInfoSectionHidden(false)
}
collectionView.verticalScrollIndicatorInsets.top = view.safeAreaInsets.top
}
fileprivate func setInfoSectionHidden(_ hidden: Bool) {
let hide = {
self.collectionView?.deleteSections(IndexSet(integer: 1))
self.sections = [.search, .customThemes, .themes]
}
let show = {
self.collectionView?.insertSections(IndexSet(integer: 1))
self.sections = [.search, .info, .customThemes, .themes]
}
collectionView.performBatchUpdates({
hidden ? hide() : show()
})
}
// MARK: - UISearchResultsUpdating
open func updateSearchResults(for searchController: UISearchController) {
searchName = searchController.searchBar.text ?? ""
}
// MARK: - NSFetchedResultsController helpers
fileprivate func searchNamePredicate() -> NSPredicate? {
guard !searchName.isEmpty else {
return nil
}
return NSPredicate(format: "name contains[c] %@", searchName)
}
fileprivate func browsePredicate() -> NSPredicate? {
return browsePredicateThemesWithCustomValue(false)
}
fileprivate func customThemesBrowsePredicate() -> NSPredicate? {
return browsePredicateThemesWithCustomValue(true)
}
fileprivate func browsePredicateThemesWithCustomValue(_ custom: Bool) -> NSPredicate? {
let blogPredicate = NSPredicate(format: "blog == %@ AND custom == %d", self.blog, custom ? 1 : 0)
let subpredicates = [blogPredicate, searchNamePredicate(), filterType.predicate].compactMap { $0 }
switch subpredicates.count {
case 1:
return subpredicates[0]
default:
return NSCompoundPredicate(andPredicateWithSubpredicates: subpredicates)
}
}
fileprivate func fetchThemes() {
do {
themesController.fetchRequest.predicate = browsePredicate()
try themesController.performFetch()
if self.blog.supports(BlogFeature.customThemes) {
customThemesController.fetchRequest.predicate = customThemesBrowsePredicate()
try customThemesController.performFetch()
}
} catch {
DDLogError("Error fetching themes: \(error)")
}
}
// MARK: - NSFetchedResultsControllerDelegate
open func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
reloadThemes()
}
// MARK: - ThemePresenter
// optional closure that will be executed when the presented WebkitViewController closes
@objc var onWebkitViewControllerClose: (() -> Void)?
@objc open func activateTheme(_ theme: Theme?) {
guard let theme = theme, !theme.isCurrentTheme() else {
return
}
updateActivateButton(isLoading: true)
_ = themeService.activate(theme,
for: blog,
success: { [weak self] (theme: Theme?) in
WPAppAnalytics.track(.themesChangedTheme, withProperties: ["theme_id": theme?.themeId ?? ""], with: self?.blog)
self?.collectionView?.reloadData()
let successTitle = NSLocalizedString("Theme Activated", comment: "Title of alert when theme activation succeeds")
let successFormat = NSLocalizedString("Thanks for choosing %@ by %@", comment: "Message of alert when theme activation succeeds")
let successMessage = String(format: successFormat, theme?.name ?? "", theme?.author ?? "")
let manageTitle = NSLocalizedString("Manage site", comment: "Return to blog screen action when theme activation succeeds")
let okTitle = NSLocalizedString("OK", comment: "Alert dismissal title")
self?.updateActivateButton(isLoading: false)
let alertController = UIAlertController(title: successTitle,
message: successMessage,
preferredStyle: .alert)
alertController.addActionWithTitle(manageTitle,
style: .default,
handler: { [weak self] (action: UIAlertAction) in
_ = self?.navigationController?.popViewController(animated: true)
})
alertController.addDefaultActionWithTitle(okTitle, handler: nil)
alertController.presentFromRootViewController()
},
failure: { [weak self] (error) in
DDLogError("Error activating theme \(String(describing: theme.themeId)): \(String(describing: error?.localizedDescription))")
let errorTitle = NSLocalizedString("Activation Error", comment: "Title of alert when theme activation fails")
let okTitle = NSLocalizedString("OK", comment: "Alert dismissal title")
self?.activityIndicator.stopAnimating()
self?.activateButton?.customView = nil
let alertController = UIAlertController(title: errorTitle,
message: error?.localizedDescription,
preferredStyle: .alert)
alertController.addDefaultActionWithTitle(okTitle, handler: nil)
alertController.presentFromRootViewController()
})
}
@objc open func installThemeAndPresentCustomizer(_ theme: Theme) {
_ = themeService.installTheme(theme,
for: blog,
success: { [weak self] in
self?.presentUrlForTheme(theme, url: theme.customizeUrl(), activeButton: !theme.isCurrentTheme())
}, failure: nil)
}
@objc open func presentCustomizeForTheme(_ theme: Theme?) {
WPAppAnalytics.track(.themesCustomizeAccessed, with: self.blog)
QuickStartTourGuide.shared.visited(.customize)
presentUrlForTheme(theme, url: theme?.customizeUrl(), activeButton: false, modalStyle: .fullScreen)
}
@objc open func presentPreviewForTheme(_ theme: Theme?) {
WPAppAnalytics.track(.themesPreviewedSite, with: self.blog)
// In order to Try & Customize a theme we first need to install it (Jetpack sites)
if let theme = theme, self.blog.supports(.customThemes) && !theme.custom {
installThemeAndPresentCustomizer(theme)
} else {
presentUrlForTheme(theme, url: theme?.customizeUrl(), activeButton: !(theme?.isCurrentTheme() ?? true))
}
}
@objc open func presentDetailsForTheme(_ theme: Theme?) {
WPAppAnalytics.track(.themesDetailsAccessed, with: self.blog)
presentUrlForTheme(theme, url: theme?.detailsUrl())
}
@objc open func presentSupportForTheme(_ theme: Theme?) {
WPAppAnalytics.track(.themesSupportAccessed, with: self.blog)
presentUrlForTheme(theme, url: theme?.supportUrl())
}
@objc open func presentViewForTheme(_ theme: Theme?) {
WPAppAnalytics.track(.themesDemoAccessed, with: self.blog)
presentUrlForTheme(theme, url: theme?.viewUrl(), onClose: onWebkitViewControllerClose)
}
@objc open func presentUrlForTheme(_ theme: Theme?, url: String?, activeButton: Bool = true, modalStyle: UIModalPresentationStyle = .pageSheet, onClose: (() -> Void)? = nil) {
guard let theme = theme, let url = url.flatMap(URL.init(string:)) else {
return
}
suspendedSearch = searchName
presentingTheme = theme
let configuration = WebViewControllerConfiguration(url: url)
configuration.authenticate(blog: theme.blog)
configuration.secureInteraction = true
configuration.customTitle = theme.name
configuration.navigationDelegate = customizerNavigationDelegate
configuration.onClose = onClose
let title = activeButton ? ThemeAction.activate.title : ThemeAction.active.title
activateButton = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(ThemeBrowserViewController.activatePresentingTheme))
activateButton?.isEnabled = !theme.isCurrentTheme()
let webViewController = WebViewControllerFactory.controller(configuration: configuration, source: "theme_browser")
webViewController.navigationItem.rightBarButtonItem = activateButton
let navigation = UINavigationController(rootViewController: webViewController)
navigation.modalPresentationStyle = modalStyle
if searchController != nil && searchController.isActive {
searchController.dismiss(animated: true, completion: {
self.present(navigation, animated: true)
})
} else {
present(navigation, animated: true)
}
}
@objc open func activatePresentingTheme() {
suspendedSearch = ""
activateTheme(presentingTheme)
presentingTheme = nil
}
}
// MARK: - NoResults Handling
private extension ThemeBrowserViewController {
func updateResults() {
if themeCount == 0 && customThemeCount == 0 {
showNoResults()
} else {
hideNoResults()
}
}
func showNoResults() {
guard !noResultsShown else {
return
}
if noResultsViewController == nil {
noResultsViewController = NoResultsViewController.controller()
}
guard let noResultsViewController = noResultsViewController else {
return
}
if searchController.isActive {
noResultsViewController.configureForNoSearchResults(title: NoResultsTitles.noThemes)
} else {
noResultsViewController.configure(title: NoResultsTitles.fetchingThemes, accessoryView: NoResultsViewController.loadingAccessoryView())
}
addChild(noResultsViewController)
collectionView.addSubview(noResultsViewController.view)
noResultsViewController.view.frame = collectionView.frame
// There is a gap between the search bar and the collection view - https://github.com/wordpress-mobile/WordPress-iOS/issues/9730
// This makes the No Results View look vertically off-center. Until that is resolved, we'll adjust the NRV according to the search bar.
if searchController.isActive {
noResultsViewController.view.frame.origin.y = searchController.searchBar.bounds.height
} else {
noResultsViewController.view.frame.origin.y -= searchBarHeight
}
noResultsViewController.didMove(toParent: self)
}
func hideNoResults() {
guard noResultsShown else {
return
}
noResultsViewController?.removeFromView()
if searchController.isActive {
collectionView?.reloadData()
} else {
sections = [.search, .info, .customThemes, .themes]
collectionView?.collectionViewLayout.invalidateLayout()
}
}
}