-
-
Notifications
You must be signed in to change notification settings - Fork 866
Expand file tree
/
Copy pathExploreViewController.swift
More file actions
1827 lines (1481 loc) · 76.3 KB
/
ExploreViewController.swift
File metadata and controls
1827 lines (1481 loc) · 76.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import WMF
import SwiftUI
import CocoaLumberjackSwift
import WMFComponents
import WMFData
class ExploreViewController: ColumnarCollectionViewController, ExploreCardViewControllerDelegate, CollectionViewUpdaterDelegate, ImageScaleTransitionProviding, DetailTransitionSourceProviding, MEPEventsProviding, WMFNavigationBarConfiguring, SearchResultsHosting {
public var presentedContentGroupKey: String?
public var shouldRestoreScrollPosition = false
@objc public weak var notificationsCenterPresentationDelegate: NotificationsCenterPresentationDelegate?
private weak var imageRecommendationsViewModel: WMFImageRecommendationsViewModel?
private var yirDataController: WMFYearInReviewDataController? {
return try? WMFYearInReviewDataController()
}
private lazy var tabsCoordinator: TabsOverviewCoordinator? = { [weak self] in
guard let self, let nav = self.navigationController else { return nil }
return TabsOverviewCoordinator(
navigationController: nav,
theme: self.theme,
dataStore: self.dataStore
)
}()
// Coordinator
private var _profileCoordinator: ProfileCoordinator?
private var profileCoordinator: ProfileCoordinator? {
guard let navigationController = navigationController,
let yirCoordinator = self.yirCoordinator else {
return nil
}
guard let existingProfileCoordinator = _profileCoordinator else {
_profileCoordinator = ProfileCoordinator(navigationController: navigationController, theme: theme, dataStore: dataStore, donateSouce: .exploreProfile, logoutDelegate: self, sourcePage: ProfileCoordinatorSource.explore, yirCoordinator: yirCoordinator)
_profileCoordinator?.badgeDelegate = self
return _profileCoordinator
}
return existingProfileCoordinator
}
private var _yirCoordinator: YearInReviewCoordinator?
private var yirCoordinator: YearInReviewCoordinator? {
guard let navigationController = navigationController,
let yirDataController else {
return nil
}
guard let existingYirCoordinator = _yirCoordinator else {
_yirCoordinator = YearInReviewCoordinator(navigationController: navigationController, theme: theme, dataStore: dataStore, dataController: yirDataController)
_yirCoordinator?.badgeDelegate = self
return _yirCoordinator
}
return existingYirCoordinator
}
private var presentingSearchResults: Bool = false
var disableSearchCancelLogging: Bool = false
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
layoutManager.register(ExploreCardCollectionViewCell.self, forCellWithReuseIdentifier: ExploreCardCollectionViewCell.identifier, addPlaceholder: true)
isRefreshControlEnabled = true
collectionView.refreshControl?.layer.zPosition = 0
NotificationCenter.default.addObserver(self, selector: #selector(exploreFeedPreferencesDidSave(_:)), name: NSNotification.Name.WMFExploreFeedPreferencesDidSave, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(articleDidChange(_:)), name: NSNotification.Name.WMFArticleUpdated, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(articleDeleted(_:)), name: NSNotification.Name.WMFArticleDeleted, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(pushNotificationBannerDidDisplayInForeground(_:)), name: .pushNotificationBannerDidDisplayInForeground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(viewContextDidReset(_:)), name: NSNotification.Name.WMFViewContextDidReset, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(databaseHousekeeperDidComplete), name: .databaseHousekeeperDidComplete, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(coreDataStoreSetup), name: WMFNSNotification.coreDataStoreSetup, object: nil)
setupTopSafeAreaOverlay(scrollView: collectionView)
}
@objc var isGranularUpdatingEnabled: Bool = true {
didSet {
collectionViewUpdater?.isGranularUpdatingEnabled = isGranularUpdatingEnabled
}
}
deinit {
NotificationCenter.default.removeObserver(self)
NSObject.cancelPreviousPerformRequests(withTarget: self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startMonitoringReachabilityIfNeeded()
showOfflineEmptyViewIfNeeded()
imageScaleTransitionView = nil
detailTransitionSourceRect = nil
logFeedImpressionAfterDelay()
dataStore.remoteNotificationsController.loadNotifications(force: false)
#if UITEST
presentUITestHelperController()
#endif
presentModalsIfNeeded()
if tabBarSnapshotImage == nil {
if #available(iOS 18, *), UIDevice.current.userInterfaceIdiom == .pad {
tabBarSnapshotImage = nil
} else {
updateTabBarSnapshotImage()
}
}
ArticleTabsFunnel.shared.logIconImpression(interface: .feed, project: nil)
}
override func viewWillHaveFirstAppearance(_ animated: Bool) {
super.viewWillHaveFirstAppearance(animated)
setupFetchedResultsController()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isGranularUpdatingEnabled = true
restoreScrollPositionIfNeeded()
configureNavigationBar()
restoreLogoStateForCurrentScrollPosition(scrollView: collectionView)
}
override func viewWillTransition(to size: CGSize, with coordinator: any UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { [weak self] _ in
self?.updateTabBarSnapshotImage()
self?.calculateTopSafeAreaOverlayHeight()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if !isMovingFromParent {
disableSearchCancelLogging = true
}
navigationItem.searchController = nil
disableSearchCancelLogging = false
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
dataStore.feedContentController.dismissCollapsedContentGroups()
stopMonitoringReachability()
isGranularUpdatingEnabled = false
resetNavBarAppearance()
}
open override func refresh() {
updateFeedSources(with: nil, userInitiated: true) {
}
}
private func presentUITestHelperController() {
let viewController = UITestHelperViewController(theme: theme)
present(viewController, animated: false)
}
@objc private func databaseHousekeeperDidComplete() {
DispatchQueue.main.async {
self.refresh()
}
}
// MARK: Navigation Bar
private func configureNavigationBar() {
let titleConfig: WMFNavigationBarTitleConfig = WMFNavigationBarTitleConfig(title: CommonStrings.exploreTabTitle, customView: nil, alignment: .leadingCompact)
let profileButtonConfig = profileButtonConfig(target: self, action: #selector(userDidTapProfile), dataStore: dataStore, yirDataController: yirDataController, leadingBarButtonItem: nil)
let tabsButtonConfig = tabsButtonConfig(target: self, action: #selector(userDidTapTabs), dataStore: dataStore)
let searchResultsVC = SearchResultsViewController(source: .topOfFeed, dataStore: dataStore)
searchResultsVC.apply(theme: theme)
searchResultsVC.parentSearchControllerDelegate = self
searchResultsVC.populateSearchBarAction = { [weak self] searchTerm in
guard let searchBar = self?.navigationItem.searchController?.searchBar else { return }
searchBar.text = searchTerm
searchBar.becomeFirstResponder()
}
searchResultsVC.articleTappedAction = { [weak self] articleURL, needsNewTab in
guard let self, let navVC = navigationController else { return }
let coordinator = LinkCoordinator(
navigationController: navVC,
url: articleURL,
dataStore: dataStore,
theme: theme,
articleSource: .search,
tabConfig: needsNewTab ? .appendArticleAndAssignNewTabAndSetToCurrent : .appendArticleAndAssignCurrentTab
)
let success = coordinator.start()
if !success {
navigate(to: articleURL)
}
}
let searchConfig = WMFNavigationBarSearchConfig(
searchResultsController: searchResultsVC,
searchControllerDelegate: searchResultsVC,
searchResultsUpdater: searchResultsVC,
searchBarDelegate: nil,
searchBarPlaceholder: CommonStrings.searchBarPlaceholder,
showsScopeBar: false, scopeButtonTitles: nil)
configureNavigationBar(titleConfig: titleConfig, closeButtonConfig: nil, profileButtonConfig: profileButtonConfig, tabsButtonConfig: tabsButtonConfig, searchBarConfig: searchConfig, hideNavigationBarOnScroll: !presentingSearchResults)
navigationItem.backButtonTitle = CommonStrings.exploreTabTitle
// Set up logo as left bar button item
let logoBarButtonItem = UIBarButtonItem(image: UIImage(named: "wikipedia"), style: .plain, target: self, action: #selector(titleBarButtonPressed(_:)))
if #available(iOS 26.0, *) {
logoBarButtonItem.hidesSharedBackground = true
logoBarButtonItem.sharesBackground = false
}
logoBarButtonItem.accessibilityLabel = WMFLocalizedString("home-title-accessibility-label", value: "Wikipedia, scroll to top of Explore", comment: "Accessibility heading for the Explore page, indicating that tapping it will scroll to the top of the explore page. \"Explore\" is the same as {{msg-wikimedia|Wikipedia-ios-welcome-explore-title}}.")
navigationItem.leftBarButtonItem = logoBarButtonItem
if #unavailable(iOS 26.0) {
logoBarButtonItem.tintColor = theme.colors.logoTintColor
}
}
@objc func updateProfileButton() {
let config = self.profileButtonConfig(target: self, action: #selector(userDidTapProfile), dataStore: dataStore, yirDataController: yirDataController, leadingBarButtonItem: nil)
updateNavigationBarProfileButton(needsBadge: config.needsBadge, needsBadgeLabel: CommonStrings.profileButtonBadgeTitle, noBadgeLabel: CommonStrings.profileButtonTitle)
}
@objc func userDidTapTabs() {
tabsCoordinator?.start()
ArticleTabsFunnel.shared.logIconClick(interface: .feed, project: nil)
}
@objc func scrollToTop() {
navigationController?.setNavigationBarHidden(false, animated: true)
collectionView.setContentOffset(CGPoint(x: collectionView.contentOffset.x, y: 0 - collectionView.contentInset.top), animated: true)
}
@objc func titleBarButtonPressed(_ sender: UIButton?) {
scrollToTop()
}
@objc func userDidTapProfile() {
guard let languageCode = dataStore.languageLinkController.appLanguage?.languageCode,
let metricsID = DonateCoordinator.metricsID(for: .exploreProfile, languageCode: languageCode) else {
return
}
DonateFunnel.shared.logExploreProfile(metricsID: metricsID)
profileCoordinator?.start()
}
// MARK: - Scroll
private func restoreScrollPositionIfNeeded() {
guard
shouldRestoreScrollPosition,
let presentedContentGroupKey = presentedContentGroupKey,
let contentGroup = fetchedResultsController?.fetchedObjects?.first(where: { $0.key == presentedContentGroupKey }),
let indexPath = fetchedResultsController?.indexPath(forObject: contentGroup)
else {
return
}
collectionView.scrollToItem(at: indexPath, at: [], animated: false)
self.shouldRestoreScrollPosition = false
self.presentedContentGroupKey = nil
}
var isLoadingOlderContent: Bool = false
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
calculateNavigationBarHiddenState(scrollView: scrollView)
updateLogoImageOnScroll(scrollView: scrollView)
guard !isLoadingOlderContent else {
return
}
let ratio: CGFloat = scrollView.contentOffset.y / (scrollView.contentSize.height - scrollView.bounds.size.height)
if ratio < 0.8 {
return
}
let lastSectionIndex = numberOfSectionsInExploreFeed - 1
guard lastSectionIndex >= 0 else {
return
}
let lastItemIndex = numberOfItemsInSection(lastSectionIndex) - 1
guard lastItemIndex >= 0 else {
return
}
guard let lastGroup = group(at: IndexPath(item: lastItemIndex, section: lastSectionIndex)) else {
return
}
let now = Date()
let midnightUTC: Date = (now as NSDate).wmf_midnightUTCDateFromLocal
guard let lastGroupMidnightUTC = lastGroup.midnightUTCDate else {
return
}
let calendar = NSCalendar.wmf_gregorian()
let days: Int = calendar?.wmf_days(from: lastGroupMidnightUTC, to: midnightUTC) ?? 0
guard days < Int(WMFExploreFeedMaximumNumberOfDays) else {
return
}
guard let nextOldestDate: Date = calendar?.date(byAdding: .day, value: -1, to: lastGroupMidnightUTC, options: .matchStrictly) else {
return
}
isLoadingOlderContent = true
updateFeedSources(with: (nextOldestDate as NSDate).wmf_midnightLocalDateForEquivalentUTC, userInitiated: false) {
self.isLoadingOlderContent = false
}
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
logFeedImpressionAfterDelay()
}
func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
navigationController?.setNavigationBarHidden(false, animated: true)
}
// MARK: - Event logging
private func logFeedImpressionAfterDelay() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(logFeedImpression), object: nil)
perform(#selector(logFeedImpression), with: self, afterDelay: 3)
}
@objc private func logFeedImpression() {
for indexPath in collectionView.indexPathsForVisibleItems {
guard let group = group(at: indexPath), group.undoType == .none, let itemFrame = collectionView.layoutAttributesForItem(at: indexPath)?.frame else {
continue
}
let navBarVisibleHeight = CGFloat(0)
let visibleRectOrigin = CGPoint(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y + navBarVisibleHeight)
let visibleRectSize = view.layoutMarginsGuide.layoutFrame.size
let itemCenter = CGPoint(x: itemFrame.midX, y: itemFrame.midY)
let visibleRect = CGRect(origin: visibleRectOrigin, size: visibleRectSize)
let isUnobstructed = visibleRect.contains(itemCenter)
guard isUnobstructed else {
continue
}
}
}
// MARK: - Search
@objc func ensureWikipediaSearchIsShowing() {
navigationController?.setNavigationBarHidden(false, animated: true)
}
// MARK: - State
@objc var dataStore: MWKDataStore!
private var fetchedResultsController: NSFetchedResultsController<WMFContentGroup>?
private var collectionViewUpdater: CollectionViewUpdater<WMFContentGroup>?
private var wantsDeleteInsertOnNextItemUpdate: Bool = false
private func setupFetchedResultsController() {
let fetchRequest: NSFetchRequest<WMFContentGroup> = WMFContentGroup.fetchRequest()
let today = NSDate().wmf_midnightUTCDateFromLocal as Date
let oldestDate = Calendar.current.date(byAdding: .day, value: -WMFExploreFeedMaximumNumberOfDays, to: today) ?? today
fetchRequest.predicate = NSPredicate(format: "isVisible == YES && (placement == NULL || placement == %@) && midnightUTCDate >= %@", "feed", oldestDate as NSDate)
fetchRequest.sortDescriptors = dataStore.feedContentController.exploreFeedSortDescriptors()
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: dataStore.viewContext, sectionNameKeyPath: "midnightUTCDate", cacheName: nil)
fetchedResultsController = frc
let updater = CollectionViewUpdater(fetchedResultsController: frc, collectionView: collectionView)
collectionViewUpdater = updater
updater.delegate = self
updater.isSlidingNewContentInFromTheTopEnabled = true
updater.performFetch()
}
private func group(at indexPath: IndexPath) -> WMFContentGroup? {
guard let frc = fetchedResultsController, frc.isValidIndexPath(indexPath) else {
return nil
}
return frc.object(at: indexPath)
}
private func groupKey(at indexPath: IndexPath) -> WMFInMemoryURLKey? {
return group(at: indexPath)?.inMemoryKey
}
lazy var saveButtonsController: SaveButtonsController = {
let sbc = SaveButtonsController(dataStore: dataStore)
sbc.delegate = self
return sbc
}()
var numberOfSectionsInExploreFeed: Int {
guard let sections = fetchedResultsController?.sections else {
return 0
}
return sections.count
}
func numberOfItemsInSection(_ section: Int) -> Int {
guard let sections = fetchedResultsController?.sections, sections.count > section else {
return 0
}
return sections[section].numberOfObjects
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return numberOfSectionsInExploreFeed
}
private func resetRefreshControl() {
guard let refreshControl = collectionView.refreshControl,
refreshControl.isRefreshing else {
return
}
refreshControl.endRefreshing()
}
lazy var reachabilityNotifier: ReachabilityNotifier = {
let notifier = ReachabilityNotifier(Configuration.current.defaultSiteDomain) { [weak self] (reachable, flags) in
if reachable {
DispatchQueue.main.async {
self?.updateFeedSources(userInitiated: false)
}
} else {
DispatchQueue.main.async {
self?.showOfflineEmptyViewIfNeeded()
}
}
}
return notifier
}()
private func stopMonitoringReachability() {
reachabilityNotifier.stop()
}
private func startMonitoringReachabilityIfNeeded() {
guard numberOfSectionsInExploreFeed == 0 else {
stopMonitoringReachability()
return
}
reachabilityNotifier.start()
}
private func showOfflineEmptyViewIfNeeded() {
guard isViewLoaded && fetchedResultsController != nil else {
return
}
guard numberOfSectionsInExploreFeed == 0 else {
wmf_hideEmptyView()
return
}
guard !wmf_isShowingEmptyView() else {
return
}
guard !reachabilityNotifier.isReachable else {
return
}
resetRefreshControl()
wmf_showEmptyView(of: .noFeed, theme: theme, frame: view.bounds)
}
var isLoadingNewContent = false
@objc(updateFeedSourcesWithDate:userInitiated:completion:)
public func updateFeedSources(with date: Date? = nil, userInitiated: Bool, completion: @escaping () -> Void = { }) {
assert(Thread.isMainThread)
guard !isLoadingNewContent else {
completion()
return
}
isLoadingNewContent = true
if date == nil, let refreshControl = collectionView.refreshControl, !refreshControl.isRefreshing {
refreshControl.beginRefreshing()
if numberOfSectionsInExploreFeed == 0 {
scrollToTop()
}
}
self.dataStore.feedContentController.updateFeedSources(with: date, userInitiated: userInitiated) {
DispatchQueue.main.async {
self.isLoadingNewContent = false
self.resetRefreshControl()
if date == nil {
self.startMonitoringReachabilityIfNeeded()
self.showOfflineEmptyViewIfNeeded()
}
completion()
}
}
}
override func contentSizeCategoryDidChange(_ notification: Notification?) {
layoutCache.reset()
super.contentSizeCategoryDidChange(notification)
}
// MARK: - ImageScaleTransitionProviding
var imageScaleTransitionView: UIImageView?
// MARK: - DetailTransitionSourceProviding
var detailTransitionSourceRect: CGRect?
var tabBarSnapshotImage: UIImage?
private func updateTabBarSnapshotImage() {
guard let tabBar = self.tabBarController?.tabBar else {
return
}
let renderer = UIGraphicsImageRenderer(size: tabBar.bounds.size)
let image = renderer.image { ctx in
tabBar.drawHierarchy(in: tabBar.bounds, afterScreenUpdates: true)
}
self.tabBarSnapshotImage = image
}
// MARK: - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfItemsInSection(section)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let maybeCell = collectionView.dequeueReusableCell(withReuseIdentifier: ExploreCardCollectionViewCell.identifier, for: indexPath)
guard let cell = maybeCell as? ExploreCardCollectionViewCell else {
return maybeCell
}
cell.apply(theme: theme)
configure(cell: cell, forItemAt: indexPath, layoutOnly: false)
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard kind == UICollectionView.elementKindSectionHeader else {
abort()
}
guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionViewHeader.identifier, for: indexPath) as? CollectionViewHeader else {
abort()
}
configureHeader(header, for: indexPath.section)
return header
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard let group = group(at: indexPath) else {
return false
}
return group.isSelectable
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var titleAreaTapped = false
if let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell {
detailTransitionSourceRect = view.convert(cell.frame, from: collectionView)
if
let vc = cell.cardContent as? ExploreCardViewController,
vc.collectionView.numberOfSections > 0, vc.collectionView.numberOfItems(inSection: 0) > 0,
let cell = vc.collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) as? ArticleCollectionViewCell {
imageScaleTransitionView = cell.imageView.isHidden ? nil : cell.imageView
} else {
imageScaleTransitionView = nil
}
titleAreaTapped = cell.titleAreaTapped
}
guard let group = group(at: indexPath) else {
return
}
presentedContentGroupKey = group.key
// When a random article title is tapped, show the previewed article, not another random article
let useRandomArticlePreviewItem = titleAreaTapped && group.moreType == .pageWithRandomButton
if !useRandomArticlePreviewItem {
// first try random coordinator
if let navigationController,
group.contentGroupKind == .random,
let randomSiteURL = group.siteURL {
// let articleSource = Explore tapped "Another random article" title
let randomCoordinator = RandomArticleCoordinator(navigationController: navigationController, articleURL: nil, siteURL: randomSiteURL, dataStore: dataStore, theme: theme, source: .undefined, animated: true)
randomCoordinator.start()
return
} else if let vc = group.detailViewControllerWithDataStore(dataStore, theme: theme, imageRecDelegate: self, imageRecLoggingDelegate: self) {
if vc is WMFImageRecommendationsViewController {
ImageRecommendationsFunnel.shared.logExploreCardDidTapAddImage()
}
push(vc, animated: true)
return
}
}
if let vc = group.detailViewControllerForPreviewItemAtIndex(0, dataStore: dataStore, theme: theme, source: .undefined) {
if vc is WMFImageGalleryViewController {
present(vc, animated: true)
} else {
push(vc, animated: true)
}
return
}
}
func configureHeader(_ header: CollectionViewHeader, for sectionIndex: Int) {
guard collectionView(collectionView, numberOfItemsInSection: sectionIndex) > 0 else {
return
}
guard let group = group(at: IndexPath(item: 0, section: sectionIndex)) else {
return
}
header.title = (group.midnightUTCDate as NSDate?)?.wmf_localizedRelativeDateFromMidnightUTCDate()
header.apply(theme: theme)
}
func createNewCardVCFor(_ cell: ExploreCardCollectionViewCell) -> ExploreCardViewController {
let cardVC = ExploreCardViewController()
cardVC.delegate = self
cardVC.dataStore = dataStore
cardVC.view.autoresizingMask = []
addChild(cardVC)
cell.cardContent = cardVC
cardVC.didMove(toParent: self)
return cardVC
}
func configure(cell: ExploreCardCollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) {
let cardVC = cell.cardContent as? ExploreCardViewController ?? createNewCardVCFor(cell)
guard let group = group(at: indexPath) else {
return
}
cardVC.contentGroup = group
cell.title = group.headerTitle
cell.subtitle = group.headerSubTitle
cell.footerTitle = cardVC.footerText
cell.isCustomizationButtonHidden = !(group.contentGroupKind.isCustomizable || group.contentGroupKind.isGlobal)
cell.undoType = group.undoType
cell.apply(theme: theme)
cell.delegate = self
if group.undoType == .contentGroupKind {
indexPathsForCollapsedCellsThatCanReappear.insert(indexPath)
}
}
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
self.theme = theme
tabBarSnapshotImage = nil
collectionView.backgroundColor = .clear
view.backgroundColor = theme.colors.paperBackground
for cell in collectionView.visibleCells {
guard let themeable = cell as? Themeable else {
continue
}
themeable.apply(theme: theme)
}
for header in collectionView.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionHeader) {
guard let themeable = header as? Themeable else {
continue
}
themeable.apply(theme: theme)
}
yirCoordinator?.theme = theme
profileCoordinator?.theme = theme
updateProfileButton()
themeNavigationBarLeadingTitleView()
themeNavigationBarCustomCenteredTitleView()
if let searchResultsVC = navigationItem.searchController?.searchResultsController as? SearchResultsViewController {
searchResultsVC.theme = theme
searchResultsVC.apply(theme: theme)
}
themeTopSafeAreaOverlay()
if #unavailable(iOS 26.0) {
navigationItem.leftBarButtonItem?.tintColor = theme.colors.logoTintColor
}
}
// MARK: - ColumnarCollectionViewLayoutDelegate
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
guard let group = group(at: indexPath) else {
return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: 0)
}
let identifier = ExploreCardCollectionViewCell.identifier
let userInfo = "evc-cell-\(group.inMemoryKey?.userInfoString ?? "")"
if let cachedHeight = layoutCache.cachedHeightForCellWithIdentifier(identifier, columnWidth: columnWidth, userInfo: userInfo) {
return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: cachedHeight)
}
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 100)
guard let placeholderCell = layoutManager.placeholder(forCellWithReuseIdentifier: ExploreCardCollectionViewCell.identifier) as? ExploreCardCollectionViewCell else {
return estimate
}
configure(cell: placeholderCell, forItemAt: indexPath, layoutOnly: true)
estimate.height = placeholderCell.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height
estimate.precalculated = true
layoutCache.setHeight(estimate.height, forCellWithIdentifier: identifier, columnWidth: columnWidth, groupKey: group.inMemoryKey, userInfo: userInfo)
return estimate
}
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForHeaderInSection section: Int, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
guard let group = self.group(at: IndexPath(item: 0, section: section)), let date = group.midnightUTCDate, date < Date() else {
return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: 0)
}
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 100)
guard let header = layoutManager.placeholder(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CollectionViewHeader.identifier) as? CollectionViewHeader else {
return estimate
}
configureHeader(header, for: section)
estimate.height = header.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height
estimate.precalculated = true
return estimate
}
override func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
return ColumnarCollectionViewLayoutMetrics.exploreViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins)
}
override func collectionView(_ collectionView: UICollectionView, shouldShowFooterForSection section: Int) -> Bool {
return false
}
// MARK: - ExploreCardViewControllerDelegate
func exploreCardViewController(_ exploreCardViewController: ExploreCardViewController, didSelectItemAtIndexPath indexPath: IndexPath) {
guard let contentGroup = exploreCardViewController.contentGroup else {
return
}
if let cell = exploreCardViewController.collectionView.cellForItem(at: indexPath) {
detailTransitionSourceRect = view.convert(cell.frame, from: exploreCardViewController.collectionView)
if let articleCell = cell as? ArticleCollectionViewCell, !articleCell.imageView.isHidden {
imageScaleTransitionView = articleCell.imageView
} else {
imageScaleTransitionView = nil
}
}
// First try pushing articles via coordinators
let successWithCoordinators = pushArticlesViaCoordinators(contentGroup: contentGroup, indexPath: indexPath)
if successWithCoordinators {
return
}
// If that didn't work (probably not pushing to an article), fall back to legacy logic
guard let vc = contentGroup.detailViewControllerForPreviewItemAtIndex(indexPath.row, dataStore: dataStore, theme: theme, source: .undefined, imageRecDelegate: self, imageRecLoggingDelegate: self) else {
return
}
if let otdvc = vc as? OnThisDayViewController {
otdvc.initialEvent = (contentGroup.contentPreview as? [Any])?[indexPath.item] as? WMFFeedOnThisDayEvent
}
if vc is WMFImageRecommendationsViewController {
ImageRecommendationsFunnel.shared.logExploreCardDidTapAddImage()
}
presentedContentGroupKey = contentGroup.key
switch contentGroup.detailType {
case .gallery:
present(vc, animated: true)
default:
push(vc, animated: true)
}
}
private func pushArticlesViaCoordinators(contentGroup: WMFContentGroup, indexPath: IndexPath) -> Bool {
// First try pushing articles via coordinators
if let navigationController,
let articleURL = contentGroup.previewArticleURLForItemAtIndex(indexPath.row) {
switch contentGroup.detailType {
case .page:
let articleSource = ArticleSource.undefined
// todo: we may want to switch to get article source if we want to be more specific:
switch contentGroup.contentGroupKind {
case .featuredArticle:
// articleSource = explore featured article cell, etc.
break
default:
break
}
let articleCoordinator = ArticleCoordinator(navigationController: navigationController, articleURL: articleURL, dataStore: dataStore, theme: theme, source: articleSource)
articleCoordinator.start()
return true
case .pageWithRandomButton:
let articleSource = ArticleSource.undefined
// todo: we may want to switch to get article source if we want to be more specific:
switch contentGroup.contentGroupKind {
case .random:
// articleSource = explore random article, etc.
break
default:
break
}
let randomArticleCoordinator = RandomArticleCoordinator(navigationController: navigationController, articleURL: articleURL, siteURL: nil, dataStore: dataStore, theme: theme, source: articleSource, animated: true)
randomArticleCoordinator.start()
return true
default:
break
}
}
return false
}
// MARK: - Prefetching
override func imageURLsForItemAt(_ indexPath: IndexPath) -> Set<URL>? {
guard let contentGroup = group(at: indexPath) else {
return nil
}
return contentGroup.imageURLsCompatibleWithTraitCollection(traitCollection, dataStore: dataStore)
}
#if DEBUG
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
guard motion == .motionShake else {
return
}
dataStore.feedContentController.debugChaos()
}
#endif
// MARK: - CollectionViewUpdaterDelegate
var needsReloadVisibleCells = false
var indexPathsForCollapsedCellsThatCanReappear = Set<IndexPath>()
private func reloadVisibleCells() {
for indexPath in collectionView.indexPathsForVisibleItems {
guard let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell else {
continue
}
configure(cell: cell, forItemAt: indexPath, layoutOnly: false)
}
}
func collectionViewUpdater<T: NSFetchRequestResult>(_ updater: CollectionViewUpdater<T>, didUpdate collectionView: UICollectionView) {
guard needsReloadVisibleCells else {
return
}
reloadVisibleCells()
needsReloadVisibleCells = false
layout.currentSection = nil
}
func collectionViewUpdater<T: NSFetchRequestResult>(_ updater: CollectionViewUpdater<T>, updateItemAtIndexPath indexPath: IndexPath, in collectionView: UICollectionView) {
layoutCache.invalidateGroupKey(groupKey(at: indexPath))
collectionView.collectionViewLayout.invalidateLayout()
if wantsDeleteInsertOnNextItemUpdate {
layout.currentSection = indexPath.section
collectionView.deleteItems(at: [indexPath])
collectionView.insertItems(at: [indexPath])
} else {
needsReloadVisibleCells = true
}
}
// MARK: Event logging
var eventLoggingCategory: EventCategoryMEP {
return .feed
}
var eventLoggingLabel: EventLabelMEP? {
return previewed.context?.getAnalyticsLabel()
}
// MARK: - For NestedCollectionViewContextMenuDelegate
private var previewed: (context: WMFContentGroup?, indexPathItem: Int?)
func contextMenu(contentGroup: WMFContentGroup? = nil, articleURL: URL? = nil, article: WMFArticle? = nil, itemIndex: Int) -> UIContextMenuConfiguration? {
guard let contentGroup = contentGroup else {
return nil
}
var previewVC: UIViewController? = viewController(for: contentGroup, at: itemIndex)
if let articleURL,
let article {
switch contentGroup.detailType {
case .page:
previewVC = ArticlePeekPreviewViewController(articleURL: articleURL, article: article, dataStore: dataStore, theme: theme, articlePreviewingDelegate: self)
case .pageWithRandomButton:
previewVC = ArticlePeekPreviewViewController(articleURL: articleURL, article: article, dataStore: dataStore, theme: theme, articlePreviewingDelegate: self, needsRandomOnPush: true)
default:
break
}
}
let previewProvider: () -> UIViewController? = {
return previewVC
}
return UIContextMenuConfiguration(identifier: nil, previewProvider: previewProvider) { (suggestedActions) -> UIMenu? in
if let previewVC = previewVC as? ArticlePeekPreviewViewController {
return UIMenu(title: "", image: nil, identifier: nil, options: [], children: previewVC.contextMenuItems)
} else {
return nil
}
}
}
func viewController(for contentGroup: WMFContentGroup, at itemIndex: Int) -> UIViewController? {
previewed.context = contentGroup
if let viewControllerToCommit = contentGroup.detailViewControllerForPreviewItemAtIndex(itemIndex, dataStore: dataStore, theme: theme, source: .undefined) {
if let potd = viewControllerToCommit as? WMFImageGalleryViewController {
potd.setOverlayViewTopBarHidden(true)
} else if let otdVC = viewControllerToCommit as? OnThisDayViewController {
otdVC.initialEvent = (contentGroup.contentPreview as? [Any])?[itemIndex] as? WMFFeedOnThisDayEvent
}
previewed.indexPathItem = itemIndex
return viewControllerToCommit
} else if contentGroup.contentGroupKind != .random {
return contentGroup.detailViewControllerWithDataStore(dataStore, theme: theme)
} else {
return nil
}
}
func willCommitPreview(with animator: UIContextMenuInteractionCommitAnimating) {
guard let viewControllerToCommit = animator.previewViewController else {
assertionFailure("Should be able to find previewed VC")
return
}
animator.addCompletion { [weak self] in
guard let self = self else {
return
}
if let potd = viewControllerToCommit as? WMFImageGalleryViewController {
potd.setOverlayViewTopBarHidden(false)
self.present(potd, animated: false)
} else if let peekVC = viewControllerToCommit as? ArticlePeekPreviewViewController {
if let navVC = navigationController {
if peekVC.needsRandomOnPush {
let coordinator = RandomArticleCoordinator(navigationController: navVC, articleURL: peekVC.articleURL, siteURL: nil, dataStore: dataStore, theme: theme, source: .undefined, animated: true)
coordinator.start()
} else {
let coordinator = ArticleCoordinator(navigationController: navVC, articleURL: peekVC.articleURL, dataStore: dataStore, theme: theme, source: .undefined)
coordinator.start()
}
}
} else {
self.push(viewControllerToCommit, animated: true)
}