-
Notifications
You must be signed in to change notification settings - Fork 687
Expand file tree
/
Copy pathMainFeedCollectionViewController.swift
More file actions
1371 lines (1133 loc) · 48.3 KB
/
MainFeedCollectionViewController.swift
File metadata and controls
1371 lines (1133 loc) · 48.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
//
// MainFeedCollectionViewController.swift
// NetNewsWire-iOS
//
// Created by Stuart Breckenridge on 23/06/2025.
// Copyright © 2025 Ranchero Software. All rights reserved.
//
import UIKit
import os
import SafariServices
import UniformTypeIdentifiers
import WebKit
import RSCore
import RSTree
import RSWeb
import Account
import Articles
private let reuseIdentifier = "FeedCell"
private let folderIdentifier = "Folder"
private let containerReuseIdentifier = "Container"
final class MainFeedCollectionViewController: UICollectionViewController, UndoableCommandRunner {
@IBOutlet var filterButton: UIBarButtonItem!
@IBOutlet var addNewItemButton: UIBarButtonItem! {
didSet {
addNewItemButton.target = self
addNewItemButton.action = #selector(MainFeedCollectionViewController.add(_:))
}
}
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainFeedCollectionViewController")
private let keyboardManager = KeyboardManager(type: .sidebar)
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 {
return true
}
var undoableCommands = [UndoableCommand]()
weak var coordinator: SceneCoordinator!
/// On iPhone, this property is used to prevent the user from selecting a new feed while the current feed is being deselected.
/// While `isAnimating` is `true`, `shouldSelectItemAt()` will not allow new selection.
/// The value is set to `true` in `viewWillAppear(_:)` if a feed is selected, and reset to `false` in
/// `viewDidAppear(_:)` after a delay to allow the deselection animation to complete.
private var isAnimating: Bool = false
var dataSource: UICollectionViewDiffableDataSource<String, SidebarItemNode>!
override func viewDidLoad() {
super.viewDidLoad()
registerForNotifications()
configureCollectionView()
configureDiffableDataSource()
collectionView.dragDelegate = self
collectionView.dropDelegate = self
becomeFirstResponder()
}
override func viewWillAppear(_ animated: Bool) {
Self.logger.debug("MainFeedCollectionViewController: viewWillAppear")
navigationController?.isToolbarHidden = false
updateUI()
super.viewWillAppear(animated)
if traitCollection.userInterfaceIdiom == .phone {
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .always
DispatchQueue.main.async {
/// This sizes the navigation bar to large.
self.navigationController?.navigationBar.sizeToFit()
}
/// On iPhone, we want to deselect the feed when the user navigates
/// back to the feeds view. To prevent the user from selecting a new feed while
/// the current feed is being deselected, set `isAnimating` to true.
///
/// `shouldSelectItemAt()` will not allow selection when `isAnimating`
/// is `true.`
if collectionView.indexPathsForSelectedItems != nil {
isAnimating = true
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.deselectIfNeccessary()
}
func deselectIfNeccessary() {
guard traitCollection.userInterfaceIdiom == .phone else {
return
}
defer {
self.isAnimating = false
}
// Pro Max may have split view in landscape — give the device some
// time to change its size class and then decide to deselect
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5043>
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
// If the iPhone is in portrait, deselect.
if UIDevice.current.orientation.isPortrait {
if self.collectionView.indexPathsForSelectedItems != nil {
self.coordinator.selectSidebarItem(indexPath: nil, animations: [.select])
}
return
}
// If the iPhone is in landscape, and the horizontal
// size class is compact, deselect.
if self.view.window?.traitCollection.horizontalSizeClass == .compact {
if self.collectionView.indexPathsForSelectedItems != nil { self.coordinator.selectSidebarItem(indexPath: nil, animations: [.select])
}
return
}
})
}
func registerForNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, 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(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(feedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil)
registerForTraitChanges([UITraitPreferredContentSizeCategory.self], target: self, action: #selector(preferredContentSizeCategoryDidChange))
}
// MARK: - Collection View Configuration
func configureCollectionView() {
let standardCellLeadingOffSet = 48.0
let indentedCellLeadingOffSet = 64.0
let useSidebarAppearance = traitCollection.userInterfaceIdiom == .pad
var config = UICollectionLayoutListConfiguration(appearance: useSidebarAppearance ? .sidebar : .insetGrouped)
config.headerMode = .supplementary
config.trailingSwipeActionsConfigurationProvider = { [unowned self] indexPath in
if indexPath.section == 0 { return UISwipeActionsConfiguration(actions: []) }
var actions = [UIContextualAction]()
// Set up the delete action
let deleteTitle = NSLocalizedString("Delete", comment: "Delete")
let deleteAction = UIContextualAction(style: .destructive, title: nil) { [weak self] _, _, completion in
self?.delete(indexPath: indexPath)
completion(true)
}
deleteAction.image = UIImage(systemName: "trash")
deleteAction.accessibilityLabel = deleteTitle
deleteAction.backgroundColor = UIColor.systemRed
actions.append(deleteAction)
// Set up the rename action
let renameTitle = NSLocalizedString("Rename", comment: "Rename")
let renameAction = UIContextualAction(style: .normal, title: nil) { [weak self] _, _, completion in
self?.rename(indexPath: indexPath)
completion(true)
}
renameAction.backgroundColor = UIColor.systemOrange
renameAction.image = UIImage(systemName: "pencil")
renameAction.accessibilityLabel = renameTitle
actions.append(renameAction)
if let feed = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? Feed {
let moreTitle = NSLocalizedString("More", comment: "More")
let moreAction = UIContextualAction(style: .normal, title: nil) { [weak self] (action, view, completion) in
if let self = self {
let alert = UIAlertController(title: feed.nameForDisplay, 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.getInfoAlertAction(indexPath: indexPath, completion: completion) {
alert.addAction(action)
}
if let action = self.homePageAlertAction(indexPath: indexPath, completion: completion) {
alert.addAction(action)
}
if let action = self.copyFeedPageAlertAction(indexPath: indexPath, completion: completion) {
alert.addAction(action)
}
if let action = self.copyHomePageAlertAction(indexPath: indexPath, completion: completion) {
alert.addAction(action)
}
if let action = self.markAllAsReadAlertAction(indexPath: indexPath, completion: completion) {
alert.addAction(action)
}
if let action = self.markUnstarredAsReadAlertAction(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.backgroundColor = UIColor.systemGray
moreAction.image = UIImage(systemName: "ellipsis")
moreAction.accessibilityLabel = moreTitle
actions.append(moreAction)
}
let config = UISwipeActionsConfiguration(actions: actions)
config.performsFirstActionWithFullSwipe = false
return config
}
config.itemSeparatorHandler = { (indexPath, sectionSeparatorConfiguration) in
var configuration = sectionSeparatorConfiguration
// Sidebar appearance: no separators
if useSidebarAppearance {
configuration.topSeparatorVisibility = .hidden
configuration.bottomSeparatorVisibility = .hidden
return configuration
}
// insetGrouped appearance: separators with proper insets
configuration.bottomSeparatorVisibility = .hidden
configuration.topSeparatorVisibility = indexPath.row == 0 ? .hidden : .visible
if let cell = self.collectionView.cellForItem(at: indexPath) as? MainFeedCollectionViewCell {
if cell.indentationLevel == 1 {
configuration.topSeparatorInsets = NSDirectionalEdgeInsets(top: 0, leading: indentedCellLeadingOffSet, bottom: 0, trailing: 0)
} else {
configuration.topSeparatorInsets = NSDirectionalEdgeInsets(top: 0, leading: standardCellLeadingOffSet, bottom: 0, trailing: 0)
}
}
if self.collectionView.cellForItem(at: indexPath) is MainFeedCollectionViewFolderCell {
configuration.topSeparatorInsets = NSDirectionalEdgeInsets(top: 0, leading: standardCellLeadingOffSet, bottom: 0, trailing: 0)
}
return configuration
}
let layout = UICollectionViewCompositionalLayout.list(using: config)
collectionView.setCollectionViewLayout(layout, animated: false)
collectionView.refreshControl = UIRefreshControl()
collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged)
if config.appearance == .sidebar {
// This defrosts the glass.
collectionView.backgroundColor = .clear
}
}
func configureDiffableDataSource() {
dataSource = UICollectionViewDiffableDataSource<String, SidebarItemNode>(
collectionView: collectionView
) { [weak self] collectionView, indexPath, sidebarItemNode -> UICollectionViewCell? in
guard let self else {
return nil
}
if sidebarItemNode.node.representedObject is Folder {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: folderIdentifier,
for: indexPath
) as! MainFeedCollectionViewFolderCell
self.configure(cell, sidebarItemNode: sidebarItemNode)
cell.delegate = self
return cell
} else {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: reuseIdentifier,
for: indexPath
) as! MainFeedCollectionViewCell
self.configure(cell, sidebarItemNode: sidebarItemNode)
return cell
}
}
dataSource.supplementaryViewProvider = { [weak self] collectionView, kind, indexPath in
guard let self else {
return nil
}
guard kind == UICollectionView.elementKindSectionHeader else {
return UICollectionReusableView()
}
let headerView = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: containerReuseIdentifier,
for: indexPath
) as! MainFeedCollectionHeaderReusableView
headerView.delegate = self
let sectionID = self.dataSource.snapshot().sectionIdentifiers[indexPath.section]
// Smart feeds section
if sectionID.isEmpty {
headerView.sectionHeaderType = .smartFeeds
headerView.headerTitle.text = SmartFeedsController.shared.nameForDisplay
headerView.unreadCount = 0
headerView.disclosureExpanded = self.coordinator.isExpanded(SmartFeedsController.shared)
return headerView
}
// Accounts
guard let account = AccountManager.shared.existingAccount(accountID: sectionID) else {
return headerView
}
headerView.sectionHeaderType = .account(sectionID)
headerView.headerTitle.text = account.nameForDisplay
headerView.unreadCount = account.unreadCount
headerView.disclosureExpanded = self.coordinator.isExpanded(account)
headerView.addInteraction(UIContextMenuInteraction(delegate: self))
return headerView
}
}
func applySnapshot(_ snapshot: NSDiffableDataSourceSnapshot<String, SidebarItemNode>, animatingDifferences: Bool, completion: (() -> Void)? = nil) {
dataSource.apply(snapshot, animatingDifferences: animatingDifferences) {
completion?()
}
}
@IBAction func settings(_ sender: UIBarButtonItem) {
coordinator.showSettings()
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
becomeFirstResponder()
coordinator.selectSidebarItem(indexPath: indexPath, animations: [.navigation, .select, .scroll])
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
// Uncomment this method to specify if the specified item should be selected
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if traitCollection.userInterfaceIdiom == .pad { return true }
return !isAnimating
}
override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return true
}
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
override func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
guard let sidebarItem = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? SidebarItem else {
return nil
}
if sidebarItem is Feed {
return makeFeedContextMenu(indexPath: indexPath, includeDeleteRename: true)
} else if sidebarItem is Folder {
return makeFolderContextMenu(indexPath: indexPath)
} else if sidebarItem is PseudoFeed {
return makePseudoFeedContextMenu(indexPath: indexPath)
} else {
return nil
}
}
// MARK: - Key Commands
// MARK: - Keyboard shortcuts
@objc func collapseAllExceptForGroupItems(_ sender: Any?) {
coordinator.collapseAllFolders()
}
@objc func collapseSelectedRows(_ sender: Any?) {
if let indexPath = coordinator.currentFeedIndexPath, let node = coordinator.nodeFor(indexPath) {
coordinator.collapse(node)
if let folder = collectionView.cellForItem(at: indexPath) as? MainFeedCollectionViewFolderCell {
folder.disclosureExpanded = false
}
}
}
@objc override func delete(_ sender: Any?) {
if let indexPath = coordinator.currentFeedIndexPath {
delete(indexPath: indexPath)
}
}
@objc func expandAll(_ sender: Any?) {
coordinator.expandAllSectionsAndFolders()
}
@objc func expandSelectedRows(_ sender: Any?) {
if let indexPath = coordinator.currentFeedIndexPath, let node = coordinator.nodeFor(indexPath) {
coordinator.expand(node)
if let folder = collectionView.cellForItem(at: indexPath) as? MainFeedCollectionViewFolderCell {
folder.disclosureExpanded = true
}
}
}
@objc func markAllAsRead(_ sender: Any) {
guard let indexPath = collectionView.indexPathsForSelectedItems?.first, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else {
return
}
let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read")
MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in
self?.coordinator.markAllAsReadInTimeline()
}
}
@objc func navigateToTimeline(_ sender: Any?) {
coordinator.navigateToTimeline()
}
@objc func openInBrowser(_ sender: Any?) {
coordinator.showBrowserForCurrentFeed()
}
@objc func selectNextDown(_ sender: Any?) {
coordinator.selectNextFeed()
}
@objc func selectNextUp(_ sender: Any?) {
coordinator.selectPrevFeed()
}
@objc func showFeedInspector(_ sender: Any?) {
coordinator.showFeedInspector()
}
// MARK: - API
func focus() {
becomeFirstResponder()
}
func updateUI() {
if coordinator.isReadFeedsFiltered {
setFilterButtonToActive()
} else {
setFilterButtonToInactive()
}
addNewItemButton?.isEnabled = !AccountManager.shared.activeAccounts.isEmpty
configureContextMenu()
}
func updateFeedSelection(animations: Animations) {
if let indexPath = coordinator.currentFeedIndexPath {
collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: animations)
} else {
if let indexPath = collectionView.indexPathsForSelectedItems?.first {
if animations.contains(.select) {
collectionView.deselectItem(at: indexPath, animated: true)
} else {
collectionView.deselectItem(at: indexPath, animated: false)
}
}
}
}
func openInAppBrowser() {
if let indexPath = coordinator.currentFeedIndexPath,
let url = coordinator.homePageURLForFeed(indexPath) {
let vc = SFSafariViewController(url: url)
vc.modalPresentationStyle = .overFullScreen
present(vc, animated: true)
}
}
func applyToAvailableCells(_ completion: (MainFeedCollectionViewCell, IndexPath) -> Void) {
for cell in collectionView.visibleCells {
guard let indexPath = collectionView.indexPath(for: cell) else {
continue
}
if let cell = collectionView.cellForItem(at: indexPath) as? MainFeedCollectionViewCell {
completion(cell, indexPath)
}
}
}
func configureIcon(_ cell: MainFeedCollectionViewCell, sidebarItem: SidebarItem) {
guard let sidebarItemID = sidebarItem.sidebarItemID else {
return
}
cell.iconImage = IconImageCache.shared.imageFor(sidebarItemID)
}
func configureIcon(_ cell: MainFeedCollectionViewFolderCell, sidebarItem: SidebarItem) {
guard let sidebarItemID = sidebarItem.sidebarItemID else {
return
}
cell.iconImage = IconImageCache.shared.imageFor(sidebarItemID)
}
func configureIcon(_ cell: MainFeedCollectionViewCell, _ indexPath: IndexPath) {
guard let sidebarItemNode = dataSource.itemIdentifier(for: indexPath),
let sidebarItem = sidebarItemNode.node.representedObject as? SidebarItem,
let sidebarItemID = sidebarItem.sidebarItemID else {
return
}
cell.iconImage = IconImageCache.shared.imageFor(sidebarItemID)
}
func configureIcon(_ cell: MainFeedCollectionViewFolderCell, _ indexPath: IndexPath) {
guard let sidebarItemNode = dataSource.itemIdentifier(for: indexPath),
let sidebarItem = sidebarItemNode.node.representedObject as? SidebarItem,
let sidebarItemID = sidebarItem.sidebarItemID else {
return
}
cell.iconImage = IconImageCache.shared.imageFor(sidebarItemID)
}
func configureCellsForRepresentedObject(_ representedObject: AnyObject) {
// applyToCellsForRepresentedObject(representedObject, configure)
}
func applyToCellsForRepresentedObject(_ representedObject: AnyObject, _ completion: (MainFeedCollectionViewCell, IndexPath) -> Void) {
applyToAvailableCells { (cell, indexPath) in
guard let sidebarItemNode = dataSource.itemIdentifier(for: indexPath),
let representedSidebarItem = representedObject as? SidebarItem,
let candidateSidebarItem = sidebarItemNode.node.representedObject as? SidebarItem,
representedSidebarItem.sidebarItemID == candidateSidebarItem.sidebarItemID else {
return
}
completion(cell, indexPath)
}
}
func restoreSelectionIfNecessary(adjustScroll: Bool) {
if let indexPath = coordinator.mainFeedIndexPathForCurrentTimeline() {
if adjustScroll {
collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: [])
} else {
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically)
}
}
}
// MARK: - Private
/// Configure feed cell.
func configure(_ cell: MainFeedCollectionViewCell, sidebarItemNode: SidebarItemNode) {
let node = sidebarItemNode.node
var indentationLevel = 0
if node.parent?.representedObject is Folder {
indentationLevel = 1
}
if let sidebarItem = node.representedObject as? SidebarItem {
cell.feedTitle.text = sidebarItem.nameForDisplay
cell.unreadCount = sidebarItem.unreadCount
cell.indentationLevel = indentationLevel
configureIcon(cell, sidebarItem: sidebarItem)
}
}
/// Configure folder cell.
func configure(_ cell: MainFeedCollectionViewFolderCell, sidebarItemNode: SidebarItemNode) {
let node = sidebarItemNode.node
if let folder = node.representedObject as? Folder {
cell.folderTitle.text = folder.nameForDisplay
cell.unreadCount = folder.unreadCount
configureIcon(cell, sidebarItem: folder)
}
if let containerID = (node.representedObject as? Container)?.containerID {
cell.setDisclosure(isExpanded: coordinator.isExpanded(containerID), animated: false)
}
}
private func findHeaderViewForAccount(_ account: Account) -> MainFeedCollectionHeaderReusableView? {
guard let sectionIndex = dataSource.snapshot().sectionIdentifiers.firstIndex(of: account.accountID) else {
return nil
}
guard sectionIndex > 0 else { // Skip smart feeds.
return nil
}
return collectionView.supplementaryView(
forElementKind: UICollectionView.elementKindSectionHeader,
at: IndexPath(item: 0, section: sectionIndex))
as? MainFeedCollectionHeaderReusableView
}
private func reloadAllVisibleCells() {
let visibleIndexPaths = collectionView.indexPathsForVisibleItems
let itemIdentifiers = visibleIndexPaths.compactMap { dataSource.itemIdentifier(for: $0) }
reloadCells(itemIdentifiers) { [weak self] in
self?.restoreSelectionIfNecessary(adjustScroll: false)
}
}
private func reloadCells(_ items: [SidebarItemNode], completion: (() -> Void)? = nil) {
guard !items.isEmpty else {
completion?()
return
}
var snapshot = dataSource.snapshot()
snapshot.reloadItems(items)
dataSource.apply(snapshot, animatingDifferences: false) {
completion?()
}
}
func setFilterButtonToActive() {
filterButton.tintColor = Assets.Colors.primaryAccent
filterButton?.accLabelText = NSLocalizedString("Selected - Filter Read Feeds", comment: "Selected - Filter Read Feeds")
}
func setFilterButtonToInactive() {
filterButton.tintColor = nil
filterButton?.accLabelText = NSLocalizedString("Filter Read Feeds", comment: "Filter Read Feeds")
}
// MARK: - Notifications
@objc func preferredContentSizeCategoryDidChange() {
IconImageCache.shared.emptyCache()
reloadAllVisibleCells()
}
@objc func unreadCountDidChange(_ note: Notification) {
updateUI()
guard let unreadCountProvider = note.object as? UnreadCountProvider else {
return
}
if let account = unreadCountProvider as? Account {
if let headerView = findHeaderViewForAccount(account) {
headerView.unreadCount = account.unreadCount
}
return
}
for cell in collectionView.visibleCells {
guard let indexPath = collectionView.indexPath(for: cell),
let sidebarItemNode = dataSource.itemIdentifier(for: indexPath),
sidebarItemNode.node.representedObject === unreadCountProvider as AnyObject else {
continue
}
if let feedCell = cell as? MainFeedCollectionViewCell {
feedCell.unreadCount = unreadCountProvider.unreadCount
}
if let folderCell = cell as? MainFeedCollectionViewFolderCell {
folderCell.unreadCount = unreadCountProvider.unreadCount
}
}
}
@objc func feedSettingDidChange(_ note: Notification) {
guard let feed = note.object as? Feed, let key = note.userInfo?[Feed.SettingUserInfoKey] as? String else {
return
}
if key == Feed.SettingKey.homePageURL || key == Feed.SettingKey.faviconURL {
configureCellsForRepresentedObject(feed)
}
}
@objc func faviconDidBecomeAvailable(_ note: Notification) {
applyToAvailableCells(configureIcon)
}
@objc func feedIconDidBecomeAvailable(_ note: Notification) {
guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed else {
return
}
applyToCellsForRepresentedObject(feed, configureIcon(_:_:))
}
// MARK: - Actions
@objc func configureContextMenu(_: Any? = nil) {
/*
Context Menu Order:
1. Add Feed
2. Add Folder
*/
var menuItems: [UIAction] = []
let addFeedActionTitle = NSLocalizedString("Add Feed", comment: "Add Feed")
let addFeedAction = UIAction(title: addFeedActionTitle, image: Assets.Images.plus) { _ in
self.coordinator.showAddFeed()
}
menuItems.append(addFeedAction)
let addFolderActionTitle = NSLocalizedString("Add Folder", comment: "Add Folder")
let addFolderAction = UIAction(title: addFolderActionTitle, image: Assets.Images.folderOutlinePlus) { _ in
self.coordinator.showAddFolder()
}
menuItems.append(addFolderAction)
let contextMenu = UIMenu(title: NSLocalizedString("Add Item", comment: "Add Item"), image: nil, identifier: nil, options: [], children: menuItems.reversed())
self.addNewItemButton.menu = contextMenu
}
@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))
}
}
@IBAction func add(_ sender: UIBarButtonItem) {
let title = NSLocalizedString("Add Item", comment: "Add Item")
let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel)
let addFeedActionTitle = NSLocalizedString("Add Feed", comment: "Add Feed")
let addFeedAction = UIAlertAction(title: addFeedActionTitle, style: .default) { _ in
self.coordinator.showAddFeed()
}
let addFolderActionTitle = NSLocalizedString("Add Folder", comment: "Add Folder")
let addFolderAction = UIAlertAction(title: addFolderActionTitle, style: .default) { _ in
self.coordinator.showAddFolder()
}
alertController.addAction(addFeedAction)
alertController.addAction(addFolderAction)
alertController.addAction(cancelAction)
alertController.popoverPresentationController?.barButtonItem = sender
present(alertController, animated: true)
}
@IBAction func toggleFilter(_ sender: Any) {
coordinator.toggleReadFeedsFilter()
}
func toggle(_ headerView: MainFeedCollectionHeaderReusableView) {
guard let sectionHeaderType = headerView.sectionHeaderType else {
return
}
let containerID: ContainerIdentifier
switch sectionHeaderType {
case .smartFeeds:
guard let id = SmartFeedsController.shared.containerID else {
return
}
containerID = id
case .account(let accountID):
guard let account = AccountManager.shared.existingAccount(accountID: accountID),
let id = account.containerID else {
return
}
containerID = id
}
if coordinator.isExpanded(containerID) {
headerView.disclosureExpanded = false
coordinator.collapse(containerID)
} else {
headerView.disclosureExpanded = true
coordinator.expand(containerID)
}
}
}
extension MainFeedCollectionViewController: MainFeedCollectionHeaderReusableViewDelegate {
func mainFeedCollectionHeaderReusableViewDidTapDisclosureIndicator(_ view: MainFeedCollectionHeaderReusableView) {
toggle(view)
}
}
extension MainFeedCollectionViewController: MainFeedCollectionViewFolderCellDelegate {
func mainFeedCollectionFolderViewCellDisclosureDidToggle(_ sender: MainFeedCollectionViewFolderCell, expanding: Bool) {
if expanding {
expand(sender)
} else {
collapse(sender)
}
}
func expand(_ cell: MainFeedCollectionViewFolderCell) {
guard let indexPath = collectionView.indexPath(for: cell),
let node = dataSource.itemIdentifier(for: indexPath)?.node else {
return
}
coordinator.expand(node)
}
func collapse(_ cell: MainFeedCollectionViewFolderCell) {
guard let indexPath = collectionView.indexPath(for: cell),
let node = dataSource.itemIdentifier(for: indexPath)?.node else {
return
}
coordinator.collapse(node)
}
}
extension MainFeedCollectionViewController: UIContextMenuInteractionDelegate {
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
guard let headerView = interaction.view as? MainFeedCollectionHeaderReusableView,
case .account(let accountID) = headerView.sectionHeaderType,
let account = AccountManager.shared.existingAccount(accountID: accountID) else {
return nil
}
return UIContextMenuConfiguration(identifier: accountID as NSCopying, previewProvider: nil) { _ in
var menuElements = [UIMenuElement]()
menuElements.append(UIMenu(title: "", options: .displayInline, children: [self.getAccountInfoAction(account: account)]))
if let markAllAction = self.markAllAsReadAction(account: account, contentView: interaction.view) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [markAllAction]))
}
if let markUnstarredAction = self.markUnstarredAsReadAction(account: account, contentView: interaction.view) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [markUnstarredAction]))
}
menuElements.append(UIMenu(title: "", options: .displayInline, children: [self.deactivateAccountAction(account: account)]))
return UIMenu(title: "", children: menuElements)
}
}
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, previewForHighlightingMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? {
guard let accountID = configuration.identifier as? String,
let sectionIndex = dataSource.snapshot().sectionIdentifiers.firstIndex(of: accountID),
let cell = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(item: 0, section: sectionIndex)) as? MainFeedCollectionHeaderReusableView else {
return nil
}
return UITargetedPreview(view: cell, parameters: CroppingPreviewParameters(view: cell))
}
}
extension MainFeedCollectionViewController {
func makeFeedContextMenu(indexPath: IndexPath, includeDeleteRename: Bool) -> UIContextMenuConfiguration {
return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [ weak self] _ in
guard let self = self else {
return nil
}
var menuElements = [UIMenuElement]()
if let inspectorAction = self.getInfoAction(indexPath: indexPath) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [inspectorAction]))
}
if let homePageAction = self.homePageAction(indexPath: indexPath) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [homePageAction]))
}
var pageActions = [UIAction]()
if let copyFeedPageAction = self.copyFeedPageAction(indexPath: indexPath) {
pageActions.append(copyFeedPageAction)
}
if let copyHomePageAction = self.copyHomePageAction(indexPath: indexPath) {
pageActions.append(copyHomePageAction)
}
if !pageActions.isEmpty {
menuElements.append(UIMenu(title: "", options: .displayInline, children: pageActions))
}
if let markAllAction = self.markAllAsReadAction(indexPath: indexPath) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [markAllAction]))
}
if let markUnstarredAction = self.markUnstarredAsReadAction(indexPath: indexPath) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [markUnstarredAction]))
}
if includeDeleteRename {
menuElements.append(UIMenu(title: "",
options: .displayInline,
children: [
self.renameAction(indexPath: indexPath),
self.deleteAction(indexPath: indexPath)
]))
}
return UIMenu(title: "", children: menuElements)
})
}
func makeFolderContextMenu(indexPath: IndexPath) -> UIContextMenuConfiguration {
return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [weak self] _ in
guard let self = self else {
return nil
}
var menuElements = [UIMenuElement]()
if let markAllAction = self.markAllAsReadAction(indexPath: indexPath) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [markAllAction]))
}
if let markUnstarredAction = self.markUnstarredAsReadAction(indexPath: indexPath) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [markUnstarredAction]))
}
menuElements.append(UIMenu(title: "",
options: .displayInline,
children: [
self.renameAction(indexPath: indexPath),
self.deleteAction(indexPath: indexPath)
]))
return UIMenu(title: "", children: menuElements)
})
}
func makePseudoFeedContextMenu(indexPath: IndexPath) -> UIContextMenuConfiguration? {
var actions = [UIAction]()
if let markAllAction = self.markAllAsReadAction(indexPath: indexPath) {
actions.append(markAllAction)
}
if let markUnstarredAction = self.markUnstarredAsReadAction(indexPath: indexPath) {
actions.append(markUnstarredAction)
}
guard !actions.isEmpty else {
return nil
}
return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { _ in
return UIMenu(title: "", children: actions)
})
}
func homePageAction(indexPath: IndexPath) -> UIAction? {
guard let feed = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? Feed,
let homePageURL = feed.homePageURL,
let url = URL(string: homePageURL) else {
return nil
}
let title = NSLocalizedString("Open Home Page", comment: "Open Home Page")
let action = UIAction(title: title, image: Assets.Images.safari) { _ in
UIApplication.shared.open(url, options: [:])
}
return action
}
func homePageAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? {