-
Notifications
You must be signed in to change notification settings - Fork 686
Expand file tree
/
Copy pathMainTimelineModernViewController.swift
More file actions
1371 lines (1132 loc) · 48.4 KB
/
MainTimelineModernViewController.swift
File metadata and controls
1371 lines (1132 loc) · 48.4 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
//
// MainTimelineModernViewController.swift
// NetNewsWire-iOS
//
// Created by Stuart Breckenridge on 25/01/2026.
// Copyright © 2026 Ranchero Software. All rights reserved.
//
import UIKit
import os
import WebKit
import RSCore
import RSWeb
import Account
import Articles
final class MainTimelineModernViewController: UIViewController, UndoableCommandRunner {
struct CellIdentifier {
static let standard = "MainTimelineCellStandard"
static let standardIndex0 = "MainTimelineCellIndexZero"
static let icon = "MainTimelineCellIcon"
static let iconIndex0 = "MainTimelineCellIconIndexZero"
}
// MARK: Private Variables
private var numberOfTextLines = 0
private var iconSize = IconSize.medium
private lazy var feedTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:)))
private lazy var filterButton = UIBarButtonItem(image: Assets.Images.filter, style: .plain, target: self, action: #selector(toggleFilter(_:)))
private lazy var firstUnreadButton = UIBarButtonItem(image: Assets.Images.nextUnread, style: .plain, target: self, action: #selector(firstUnread(_:)))
private var dataSource: UICollectionViewDiffableDataSource<Int, Article>?
var didPushArticleViewController = false
private var timelineFeed: SidebarItem? {
assert(coordinator != nil)
return coordinator?.timelineFeed
}
private var showIcons: Bool {
assert(coordinator != nil)
return coordinator?.showIcons ?? false
}
private var currentArticle: Article? {
assert(coordinator != nil)
return coordinator?.currentArticle
}
private var timelineMiddleIndexPath: IndexPath? {
get {
coordinator?.timelineMiddleIndexPath
}
set {
coordinator?.timelineMiddleIndexPath = newValue
}
}
private var isTimelineViewControllerPending: Bool {
get {
coordinator?.isTimelineViewControllerPending ?? false
}
set {
coordinator?.isTimelineViewControllerPending = newValue
}
}
private var timelineIconImage: IconImage? {
assert(coordinator != nil)
return coordinator?.timelineIconImage
}
private var timelineDefaultReadFilterType: ReadFilterType {
return timelineFeed?.defaultReadFilterType ?? .none
}
private var isReadArticlesFiltered: Bool {
assert(coordinator != nil)
return coordinator?.isReadArticlesFiltered ?? false
}
private var isTimelineUnreadAvailable: Bool {
assert(coordinator != nil)
return coordinator?.isTimelineUnreadAvailable ?? false
}
private var isRootSplitCollapsed: Bool {
assert(coordinator != nil)
return coordinator?.isRootSplitCollapsed ?? false
}
private var articles: ArticleArray? {
assert(coordinator != nil)
return coordinator?.articles
}
private lazy var navigationBarTitleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: .subheadline).bold()
label.isUserInteractionEnabled = true
label.numberOfLines = 1
label.textAlignment = .center
label.adjustsFontForContentSizeCategory = false
let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:)))
label.addGestureRecognizer(tap)
let pointerInteraction = UIPointerInteraction(delegate: nil)
label.addInteraction(pointerInteraction)
return label
}()
private lazy var navigationBarSubtitleTitleLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "Helvetica", size: 12)
label.textColor = .systemGray
label.textAlignment = .center
label.isUserInteractionEnabled = true
label.adjustsFontForContentSizeCategory = false
let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:)))
label.addGestureRecognizer(tap)
return label
}()
// MARK: Variables
weak var coordinator: SceneCoordinator?
var undoableCommands = [UndoableCommand]()
override var keyCommands: [UIKeyCommand]? {
// If the first responder is the WKWebView (PreloadedWebView) we don't want to supply any keyboard
// commands that the system is looking for by going up the responder chain. They will interfere with
// the WKWebViews built in hardware keyboard shortcuts, specifically the up and down arrow keys.
guard let current = UIResponder.currentFirstResponder, !(current is PreloadedWebView) else { return nil }
return keyboardManager.keyCommands
}
override var canBecomeFirstResponder: Bool {
true
}
// MARK: Private Constants
private let searchController = UISearchController(searchResultsController: nil)
private let keyboardManager = KeyboardManager(type: .timeline)
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainTimelineModernViewController")
// MARK: Constants
private let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0)
private let updateQueue = CoalescingQueue(name: "Timeline Update Queue", interval: 0.5, maxInterval: 1.0)
// MARK: - IBOutlets
@IBOutlet var markAllAsReadButton: UIBarButtonItem?
@IBOutlet var collectionView: UICollectionView?
override func viewDidLoad() {
super.viewDidLoad()
assert(collectionView != nil)
dataSource = makeDataSource(collectionView!)
addNotificationObservers()
assert(dataSource != nil)
configureCollectionView(dataSource!)
configureSearchController()
definesPresentationContext = true
numberOfTextLines = AppDefaults.shared.timelineNumberOfLines
iconSize = AppDefaults.shared.timelineIconSize
assert(collectionView?.refreshControl != nil)
collectionView?.refreshControl = UIRefreshControl()
collectionView?.refreshControl?.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged)
configureToolbar()
resetUI(resetScroll: true)
// Load the table and then scroll to the saved position if available
applyChanges(animated: false) {
if let restoreIndexPath = self.timelineMiddleIndexPath {
self.collectionView?.scrollToItem(at: restoreIndexPath, at: .centeredVertically, animated: false)
}
}
// Disable swipe back on iPad Mice
guard let gesture = self.navigationController?.interactivePopGestureRecognizer as? UIPanGestureRecognizer else {
return
}
gesture.allowedScrollTypesMask = []
navigationItem.title = nil // Don’t let "Timeline" accidentally show
navigationItem.largeTitleDisplayMode = .never
navigationItem.titleView = navigationBarTitleLabel
navigationItem.subtitleView = navigationBarSubtitleTitleLabel
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
Self.logger.debug("MainTimelineModernViewController: viewWillAppear")
super.viewWillAppear(animated)
self.navigationController?.isToolbarHidden = false
// If the nav bar is hidden, fade it in to avoid it showing stuff as it is getting laid out
if navigationController?.navigationBar.isHidden ?? false {
navigationController?.navigationBar.alpha = 0
}
updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "")
coordinator?.updateNavigationBarSubtitles(nil)
}
override func viewDidAppear(_ animated: Bool) {
Self.logger.debug("MainTimelineModernViewController: viewDidAppear")
super.viewDidAppear(true)
isTimelineViewControllerPending = false
if navigationController?.navigationBar.alpha == 0 {
UIView.animate(withDuration: 0.5) {
self.navigationController?.navigationBar.alpha = 1
}
}
// Deselect only when returning from article navigation
if coordinator?.isRootSplitCollapsed ?? true, didPushArticleViewController {
didPushArticleViewController = false
self.deselectIfNecessary()
}
}
func deselectIfNecessary() {
Self.logger.debug("MainTimelineModernViewController: deselectIfNecessary")
guard traitCollection.userInterfaceIdiom == .phone else {
return
}
guard let coordinator, coordinator.isRootSplitCollapsed else {
return
}
if coordinator.currentArticle != nil {
Self.logger.debug("MainTimelineModernViewController: deselectIfNecessary deselecting")
if let indexPath = collectionView?.indexPathsForSelectedItems?.first {
collectionView?.deselectItem(at: indexPath, animated: true)
}
coordinator.selectArticle(nil)
}
}
func restoreSelectionIfNecessary(adjustScroll: Bool) {
Self.logger.debug("MainTimelineModernViewController: restoreSelectionIfNecessary")
guard let collectionView else {
return
}
if let article = currentArticle, let dataSource, let indexPath = dataSource.indexPath(for: article) {
if adjustScroll {
Self.logger.debug("MainTimelineModernViewController: restoreSelectionIfNecessary selecting item and adjusting scroll")
collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: [])
} else {
let indexPaths = collectionView.indexPathsForSelectedItems ?? []
if !indexPaths.contains(indexPath) {
Self.logger.debug("MainTimelineModernViewController: restoreSelectionIfNecessary does not contain selected index path")
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically)
}
}
}
}
func updateNavigationBarTitle(_ text: String) {
navigationItem.title = text
if let label = navigationItem.titleView as? UILabel {
label.text = text
label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil)
label.sizeToFit()
}
}
func updateNavigationBarSubtitle(_ text: String) {
if let label = navigationItem.subtitleView as? UILabel {
label.text = text
label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil)
label.sizeToFit()
}
}
func reinitializeArticles(resetScroll: Bool) {
Self.logger.debug("MainTimelineModernViewController: reinitializeArticles")
guard isViewLoaded else {
return
}
resetUI(resetScroll: resetScroll)
restoreSelectionIfNecessary(adjustScroll: false)
}
func reloadArticles(animated: Bool) {
Self.logger.debug("MainTimelineModernViewController: reloadArticles")
guard isViewLoaded else {
return
}
applyChanges(animated: animated)
}
func updateArticleSelection(animations: Animations) {
Self.logger.debug("MainTimelineModernViewController: updateArticleSelection")
guard isViewLoaded, let collectionView, let dataSource else {
return
}
if let article = currentArticle,
let indexPath = dataSource.indexPath(for: article), let indexPaths = collectionView.indexPathsForSelectedItems {
if indexPaths.contains(indexPath) {
return
}
collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: animations)
} else {
collectionView.selectItem(at: nil, animated: animations.contains(.select), scrollPosition: .centeredVertically)
}
queueUpdateUI()
}
func queueUpdateUI() {
updateQueue.add(self, #selector(updateUI))
}
@objc func updateUI() {
Self.logger.debug("MainTimelineModernViewController: updateUI")
updateToolbar()
}
func hideSearch() {
navigationItem.searchController?.isActive = false
}
func showSearchAll() {
navigationItem.searchController?.isActive = true
navigationItem.searchController?.searchBar.selectedScopeButtonIndex = 1
navigationItem.searchController?.searchBar.becomeFirstResponder()
}
func focus() {
Self.logger.debug("MainTimelineModernViewController: focus")
becomeFirstResponder()
}
// MARK: - Reloading
func queueReloadAvailableCells() {
updateQueue.add(self, #selector(reloadVisibleCells))
}
@objc private func reloadVisibleCells() {
Self.logger.debug("MainTimelineModernViewController: reloadVisibleCells")
guard isViewLoaded, let collectionView, let dataSource else {
return
}
let indexPaths = collectionView.indexPathsForVisibleItems
let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) }
reloadCells(visibleArticles)
}
private func reloadCells(_ articles: [Article]) {
Self.logger.debug("MainTimelineModernViewController: reloadCells")
guard !articles.isEmpty, let dataSource else {
return
}
var snapshot = dataSource.snapshot()
snapshot.reloadItems(articles)
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.0, execute: {
guard let dataSource = self.dataSource else {
return
}
dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in
self?.restoreSelectionIfNecessary(adjustScroll: false)
}
})
}
@objc func refreshAccounts(_ sender: Any) {
collectionView?.refreshControl?.endRefreshing()
// This is a hack to make sure that an error dialog doesn't interfere with dismissing the refreshControl.
// If the error dialog appears too closely to the call to endRefreshing, then the refreshControl never disappears.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
appDelegate.manualRefresh(errorHandler: ErrorHandler.present(self))
}
}
// MARK: - Keyboard shortcuts
@objc func selectNextUp(_ sender: Any?) {
assert(coordinator != nil)
coordinator?.selectPrevArticle()
}
@objc func selectNextDown(_ sender: Any?) {
assert(coordinator != nil)
coordinator?.selectNextArticle()
}
@objc func navigateToSidebar(_ sender: Any?) {
assert(coordinator != nil)
coordinator?.navigateToFeeds()
}
@objc func navigateToDetail(_ sender: Any?) {
assert(coordinator != nil)
coordinator?.navigateToDetail()
}
@objc func showFeedInspector(_ sender: Any?) {
assert(coordinator != nil)
coordinator?.showFeedInspector()
}
// MARK: - IBActions
@objc func openInBrowser(_ sender: Any?) {
assert(coordinator != nil)
coordinator?.showBrowserForCurrentArticle()
}
@objc func openInAppBrowser(_ sender: Any?) {
assert(coordinator != nil)
coordinator?.showInAppBrowser()
}
@IBAction func toggleFilter(_ sender: Any) {
assert(coordinator != nil)
coordinator?.toggleReadArticlesFilter()
}
private func markAllAsReadInTimeline() {
assert(coordinator != nil)
coordinator?.markAllAsReadInTimeline()
}
private func markAllAsReadExceptStarredInTimeline() {
assert(coordinator != nil)
coordinator?.markAllAsReadExceptStarredInTimeline()
}
@IBAction func markAllAsRead(_ sender: Any?) {
let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read")
if let source = sender as? UIBarButtonItem {
MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: source) { [weak self] in
self?.markAllAsReadInTimeline()
}
}
if sender is UIKeyCommand {
guard let collectionView else {
return
}
guard let indexPath = collectionView.indexPathsForSelectedItems?.first, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else {
return
}
MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in
self?.markAllAsReadInTimeline()
}
}
}
@IBAction func firstUnread(_ sender: Any) {
assert(coordinator != nil)
coordinator?.selectFirstUnread()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
// MARK: - UICollectionViewDelegate
extension MainTimelineModernViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
becomeFirstResponder()
if let dataSource {
let article = dataSource.itemIdentifier(for: indexPath)
coordinator?.selectArticle(article, animations: [.scroll, .select, .navigation])
}
}
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemsAt indexPaths: [IndexPath], point: CGPoint) -> UIContextMenuConfiguration? {
guard let firstIndex = indexPaths.first, let dataSource, let article = dataSource.itemIdentifier(for: firstIndex) else { return nil }
return UIContextMenuConfiguration(identifier: firstIndex.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] _ in
guard let self = self else { return nil }
var menuElements = [UIMenuElement]()
var markActions = [UIAction]()
if let action = self.toggleArticleReadStatusAction(article) {
markActions.append(action)
}
markActions.append(self.toggleArticleStarStatusAction(article))
if let action = self.markAboveAsReadAction(article, indexPath: firstIndex) {
markActions.append(action)
}
if let action = self.markBelowAsReadAction(article, indexPath: firstIndex) {
markActions.append(action)
}
menuElements.append(UIMenu(title: "", options: .displayInline, children: markActions))
var secondaryActions = [UIAction]()
if let action = self.discloseFeedAction(article) {
secondaryActions.append(action)
}
if let action = self.markAllInFeedAsReadAction(article, indexPath: firstIndex) {
secondaryActions.append(action)
}
if let action = self.markAllAsReadExceptStarredAction(firstIndex) {
secondaryActions.append(action)
}
if !secondaryActions.isEmpty {
menuElements.append(UIMenu(title: "", options: .displayInline, children: secondaryActions))
}
var copyActions = [UIAction]()
if let action = self.copyArticleURLAction(article) {
copyActions.append(action)
}
if let action = self.copyExternalURLAction(article) {
copyActions.append(action)
}
if !copyActions.isEmpty {
menuElements.append(UIMenu(title: "", options: .displayInline, children: copyActions))
}
if let action = self.openInBrowserAction(article) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [action]))
}
if let action = self.shareAction(article, indexPath: firstIndex) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [action]))
}
return UIMenu(title: "", children: menuElements)
})
}
func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, highlightPreviewForItemAt indexPath: IndexPath) -> UITargetedPreview? {
guard let row = configuration.identifier as? Int,
let cell = collectionView.cellForItem(at: IndexPath(row: row, section: 0)) else {
return nil
}
let previewView = cell.contentView
var bounds = previewView.bounds
let parameters = UIPreviewParameters()
parameters.backgroundColor = cell.isSelected ? cell.backgroundConfiguration?.backgroundColor : .tertiarySystemBackground
if let insets = cell.backgroundConfiguration?.backgroundInsets {
bounds = bounds.inset(by: UIEdgeInsets(top: insets.top,
left: -insets.leading - 4,
bottom: insets.bottom,
right: -insets.trailing - 4))
}
parameters.visiblePath = UIBezierPath(roundedRect: bounds,
cornerRadius: 20)
return UITargetedPreview(view: cell, parameters: parameters)
}
func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, dismissalPreviewForItemAt indexPath: IndexPath) -> UITargetedPreview? {
guard let row = configuration.identifier as? Int,
let cell = collectionView.cellForItem(at: IndexPath(row: row, section: 0)) else {
return nil
}
let previewView = cell.contentView
var bounds = previewView.bounds
let parameters = UIPreviewParameters()
parameters.backgroundColor = cell.isSelected ? cell.backgroundConfiguration?.backgroundColor : .tertiarySystemBackground
if let insets = cell.backgroundConfiguration?.backgroundInsets {
bounds = bounds.inset(by: UIEdgeInsets(top: insets.top,
left: -insets.leading - 4,
bottom: insets.bottom,
right: -insets.trailing - 4))
}
parameters.visiblePath = UIBezierPath(roundedRect: bounds,
cornerRadius: 20)
return UITargetedPreview(view: cell, parameters: parameters)
}
}
// MARK: Private API
private extension MainTimelineModernViewController {
func addNotificationObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(avatarDidBecomeAvailable(_:)), name: .AvatarDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .FaviconDidBecomeAvailable, object: nil)
// TODO: fix this temporary hack, which will probably require refactoring image handling.
// We want to know when to possibly reconfigure our cells with a new image, and we don’t
// always know when an image is available — but watching the .htmlMetadataAvailable Notification
// lets us know that it’s time to request an image.
NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .htmlMetadataAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(timelineIconSizeDidChange(_:)), name: .timelineIconSizeDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(timelineNumberOfLinesDidChange(_:)), name: .timelineNumberOfLinesDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange), name: .DisplayNameDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
}
private func configureSearchController() {
// Setup the Search Controller
searchController.delegate = self
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.delegate = self
searchController.searchBar.placeholder = NSLocalizedString("Search Articles", comment: "Search Articles")
searchController.searchBar.scopeButtonTitles = [
NSLocalizedString("Here", comment: "Here"),
NSLocalizedString("All Articles", comment: "All Articles")
]
searchController.searchBar.barTintColor = .clear
searchController.searchBar.scopeBarBackgroundImage = UIImage()
searchController.searchBar.autocapitalizationType = .none
navigationItem.searchController = searchController
if traitCollection.userInterfaceIdiom == .pad {
searchController.searchBar.selectedScopeButtonIndex = 1
navigationItem.searchBarPlacementAllowsExternalIntegration = true
}
}
private func configureCollectionView(_ dataSource: UICollectionViewDiffableDataSource<Int, Article>) {
var config = UICollectionLayoutListConfiguration(appearance: .plain)
config.showsSeparators = false
config.headerMode = .none
config.trailingSwipeActionsConfigurationProvider = { [unowned self] indexPath in
guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil }
var actions = [UIContextualAction]()
// Set up the star action
let starTitle = article.status.starred ?
NSLocalizedString("Unstar", comment: "Unstar") :
NSLocalizedString("Star", comment: "Star")
let starAction = UIContextualAction(style: .normal, title: starTitle) { [weak self] _, _, completion in
/// The call to `toggleStar` is delayed in order to allow
/// the swipe animation to complete. Calling `toggleStar` with no
/// delay results UICollectionView internal inconsistency: unexpected
/// removal of the current swipe occurrence's mask view error.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.85, execute: {
self?.toggleStar(article)
})
completion(true)
}
starAction.image = article.status.starred ? Assets.Images.starOpen : Assets.Images.starClosed
starAction.backgroundColor = Assets.Colors.star
// Set up the read action
let moreTitle = NSLocalizedString("More", comment: "More")
let moreAction = UIContextualAction(style: .normal, title: moreTitle) { [weak self] (action, view, completion) in
if let self = self {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
if let popoverController = alert.popoverPresentationController {
popoverController.sourceView = view
popoverController.sourceRect = CGRect(x: view.frame.size.width/2, y: view.frame.size.height/2, width: 1, height: 1)
}
if let action = self.markAboveAsReadAlertAction(article, indexPath: indexPath, completion: completion) {
alert.addAction(action)
}
if let action = self.markBelowAsReadAlertAction(article, indexPath: indexPath, completion: completion) {
alert.addAction(action)
}
if let action = self.discloseFeedAlertAction(article, completion: completion) {
alert.addAction(action)
}
if let action = self.markAllInFeedAsReadAlertAction(article, indexPath: indexPath, completion: completion) {
alert.addAction(action)
}
if let action = self.markAllAsReadExceptStarredAlertAction(indexPath, completion: completion) {
alert.addAction(action)
}
if let action = self.openInBrowserAlertAction(article, completion: completion) {
alert.addAction(action)
}
if let action = self.shareAlertAction(article, indexPath: indexPath, completion: completion) {
alert.addAction(action)
}
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel) { _ in
completion(true)
})
self.present(alert, animated: true)
}
}
moreAction.image = Assets.Images.more
moreAction.backgroundColor = UIColor.systemGray
actions.append(starAction)
actions.append(moreAction)
let config = UISwipeActionsConfiguration(actions: actions)
config.performsFirstActionWithFullSwipe = true
return config
}
config.leadingSwipeActionsConfigurationProvider = { [unowned self] indexPath in
guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil }
guard !article.status.read || article.isAvailableToMarkUnread else { return nil }
var actions = [UIContextualAction]()
// Set up the read action
let readTitle = article.status.read ?
NSLocalizedString("Mark as Unread", comment: "Mark as Unread") :
NSLocalizedString("Mark as Read", comment: "Mark as Read")
let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] _, _, completion in
/// The call to `toggleRead` is delayed in order to allow
/// the swipe animation to complete. Calling `toggleRead` with no
/// delay results UICollectionView internal inconsistency: unexpected
/// removal of the current swipe occurrence's mask view error.
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.85, execute: {
self?.toggleRead(article)
})
completion(true)
}
readAction.image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen
readAction.backgroundColor = Assets.Colors.primaryAccent
actions.append(readAction)
let config = UISwipeActionsConfiguration(actions: actions)
config.performsFirstActionWithFullSwipe = true
return config
}
collectionView?.refreshControl = UIRefreshControl()
collectionView?.refreshControl?.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged)
collectionView?.contentInsetAdjustmentBehavior = .automatic
let layout = UICollectionViewCompositionalLayout { _, layoutEnvironment in
let listConfig = config
let section = NSCollectionLayoutSection.list(using: listConfig, layoutEnvironment: layoutEnvironment)
/// Note to future self: apply insets that affect cell width
/// calculations (leading swipe actions with sidebar visible)
section.contentInsets = NSDirectionalEdgeInsets(
top: 0,
leading: self.view.safeAreaInsets.left, // Sidebar width
bottom: 0,
trailing: 0
)
return section
}
layout.configuration.contentInsetsReference = .safeArea
collectionView?.collectionViewLayout = layout
}
private func makeDataSource(_ collectionView: UICollectionView) -> UICollectionViewDiffableDataSource<Int, Article> {
let dataSource: UICollectionViewDiffableDataSource<Int, Article> =
MainTimelineCollectionViewDataSource(collectionView: collectionView, cellProvider: { [weak self] collectionView, indexPath, article in
guard let self else {
return nil
}
let cellData = self.configure(article: article)
if self.showIcons {
if indexPath.row == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier.iconIndex0, for: indexPath) as! MainTimelineCollectionViewCell
cell.cellData = cellData
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier.icon, for: indexPath) as! MainTimelineCollectionViewCell
cell.cellData = cellData
return cell
}
} else {
if indexPath.row == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier.standardIndex0, for: indexPath) as! MainTimelineCollectionViewCell
cell.cellData = cellData
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier.standard, for: indexPath) as! MainTimelineCollectionViewCell
cell.cellData = cellData
return cell
}
}
})
return dataSource
}
@discardableResult
private func configure(article: Article) -> MainTimelineCellData {
let iconImage = iconImageFor(article)
let showFeedNames = coordinator?.showFeedNames ?? ShowFeedName.none
let showIcon = showIcons && iconImage != nil
let cellData = MainTimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: iconImage, showIcon: showIcon, numberOfLines: numberOfTextLines, iconSize: iconSize)
return cellData
}
private func iconImageFor(_ article: Article) -> IconImage? {
if !showIcons {
return nil
}
return article.iconImage()
}
func searchArticles(_ searchString: String, _ searchScope: SearchScope) {
assert(coordinator != nil)
coordinator?.searchArticles(searchString, searchScope)
}
func configureToolbar() {
if traitCollection.userInterfaceIdiom == .phone {
toolbarItems?.insert(.flexibleSpace(), at: 1)
toolbarItems?.insert(navigationItem.searchBarPlacementBarButtonItem, at: 2)
}
}
func resetUI(resetScroll: Bool) {
let shouldShowFilterButton = coordinator?.shouldShowFilterButton() ?? false
navigationItem.rightBarButtonItem = shouldShowFilterButton ? filterButton : nil
if isReadArticlesFiltered {
filterButton.style = .prominent
filterButton.tintColor = Assets.Colors.primaryAccent
filterButton.accLabelText = NSLocalizedString("Selected - Filter Read Articles", comment: "Selected - Filter Read Articles")
} else {
filterButton.style = .plain
filterButton.tintColor = nil
filterButton.accLabelText = NSLocalizedString("Filter Read Articles", comment: "Filter Read Articles")
}
collectionView?.selectItem(at: nil, animated: false, scrollPosition: .top)
if resetScroll {
if let dataSource {
let snapshot = dataSource.snapshot()
if snapshot.sectionIdentifiers.count > 0 && snapshot.itemIdentifiers(inSection: 0).count > 0 {
// collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: .top)
}
}
}
updateToolbar()
}
func updateToolbar() {
markAllAsReadButton?.isEnabled = isTimelineUnreadAvailable
firstUnreadButton.isEnabled = coordinator?.isAnyUnreadAvailable ?? false
if isRootSplitCollapsed {
if let toolbarItems = toolbarItems, toolbarItems.last != firstUnreadButton {
var items = toolbarItems
items.append(firstUnreadButton)
setToolbarItems(items, animated: false)
}
} else {
if let toolbarItems = toolbarItems, toolbarItems.last == firstUnreadButton {
let items = Array(toolbarItems[0..<toolbarItems.count - 1])
setToolbarItems(items, animated: false)
}
}
}
func applyChanges(animated: Bool, completion: (() -> Void)? = nil) {
Self.logger.debug("MainTimelineModernViewController: applyChanges")
guard let dataSource else {
return
}
var snapshot = NSDiffableDataSourceSnapshot<Int, Article>()
snapshot.appendSections([0])
snapshot.appendItems(articles ?? ArticleArray(), toSection: 0)
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
self?.restoreSelectionIfNecessary(adjustScroll: false)
completion?()
}
}
}
// MARK: - Notifications API
private extension MainTimelineModernViewController {
@objc dynamic func unreadCountDidChange(_ notification: Notification) {
Self.logger.debug("MainTimelineModernViewController: unreadCountDidChange")
queueUpdateUI()
}
@objc func statusesDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineModernViewController: statusesDidChange")
guard isViewLoaded, let collectionView, let dataSource else {
return
}
guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set<String>, !articleIDs.isEmpty else {
return
}
let indexPaths = collectionView.indexPathsForVisibleItems
if indexPaths.count == 0 {
return
}
let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) }
let visibleUpdatedArticles = visibleArticles.filter { articleIDs.contains($0.articleID) }
reloadCells(visibleUpdatedArticles)
}
@objc func feedIconDidBecomeAvailable(_ note: Notification) {
Self.logger.debug("MainTimelineModernViewController: feedIconDidBecomeAvailable")
guard isViewLoaded else {
return
}
queueReloadAvailableCells()
}
@objc func avatarDidBecomeAvailable(_ note: Notification) {
Self.logger.debug("MainTimelineModernViewController: avatarDidBecomeAvailable")
guard isViewLoaded else {
return
}
queueReloadAvailableCells()
}
@objc func faviconDidBecomeAvailable(_ note: Notification) {
Self.logger.debug("MainTimelineModernViewController: faviconDidBecomeAvailable")
guard isViewLoaded else {
return
}
queueReloadAvailableCells()
}
@objc func timelineIconSizeDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineModernViewController: timelineIconSizeDidChange")
if iconSize != AppDefaults.shared.timelineIconSize {
iconSize = AppDefaults.shared.timelineIconSize
reloadVisibleCells()
}
}
@objc func timelineNumberOfLinesDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineModernViewController: timelineNumberOfLinesDidChange")
if numberOfTextLines != AppDefaults.shared.timelineNumberOfLines {
numberOfTextLines = AppDefaults.shared.timelineNumberOfLines
reloadVisibleCells()
}
}
@objc func contentSizeCategoryDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineModernViewController: contentSizeCategoryDidChange")
reloadVisibleCells()
}
@objc func displayNameDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineModernViewController: displayNameDidChange")
updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "")
}
@objc func willEnterForeground(_ note: Notification) {
Self.logger.debug("MainTimelineModernViewController: willEnterForeground")
queueUpdateUI()
}
@objc func scrollPositionDidChange() {
Self.logger.debug("MainTimelineModernViewController: scrollPositionDidChange")
timelineMiddleIndexPath = collectionView?.middleVisibleRow()
}