Files
NetNewsWire/iOS/MainFeed/MainFeedCollectionViewController.swift

1555 lines
55 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// 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 HTMLMetadata
import Account
import ActivityLog
import Articles
import Images
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: Logger.nnwSubsystem, 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
}
// The selected row is accent-colored only while the feeds list is first responder.
@discardableResult override func becomeFirstResponder() -> Bool {
let didBecomeFirstResponder = super.becomeFirstResponder()
updateVisibleCellConfigurations()
return didBecomeFirstResponder
}
@discardableResult override func resignFirstResponder() -> Bool {
let didResignFirstResponder = super.resignFirstResponder()
updateVisibleCellConfigurations()
return didResignFirstResponder
}
private let refreshProgressView = RefreshProgressView(frame: .zero)
private var currentActivityButton: UIBarButtonItem?
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
private var isToolbarConfigured: Bool = false
// Serialized snapshot updates — see enqueueSidebarUpdate below.
private var isApplyingSnapshot = false
private var queuedSidebarUpdates = [QueuedSidebarUpdate]()
// Write via applySnapshot/reconfigureItems. Read via currentSidebarSnapshot
// and the lookup methods — in an apply completion if you need post-update state.
private var dataSource: UICollectionViewDiffableDataSource<String, SidebarItemNode>!
override func viewDidLoad() {
super.viewDidLoad()
registerForNotifications()
configureCurrentActivityButton()
configureCollectionView()
configureDiffableDataSource()
collectionView.dragDelegate = self
collectionView.dropDelegate = self
becomeFirstResponder()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
coordinator?.sidebarDidLayout()
}
func configureCurrentActivityButton() {
if #available(iOS 26, *) {
// Toolbar button to open Current Activity. It lights up while activity is happening.
let settingsButtonIndex = 0
let button = UIBarButtonItem(image: Assets.Images.currentActivity, style: .plain, target: self, action: #selector(showCurrentActivity(_:)))
button.accessibilityLabel = NSLocalizedString("Current Activity", comment: "Current Activity")
toolbarItems?.insert(button, at: settingsButtonIndex + 1)
currentActivityButton = button
NotificationCenter.default.addObserver(self, selector: #selector(activityDidChange(_:)), name: .activityDidChange, object: nil)
updateCurrentActivityButtonState()
} else {
// Tap progress view in the toolbar to open Current Activity.
refreshProgressView.isUserInteractionEnabled = true
refreshProgressView.accessibilityTraits = .button
refreshProgressView.accessibilityHint = NSLocalizedString("Shows current activity", comment: "Current Activity accessibility hint")
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showCurrentActivity(_:)))
refreshProgressView.addGestureRecognizer(tapGestureRecognizer)
}
}
@objc func activityDidChange(_ note: Notification) {
updateCurrentActivityButtonState()
}
func updateCurrentActivityButtonState() {
let hasCurrentActivity = !ActivityLog.shared.runningActivities.isEmpty || !ActivityLog.shared.pendingActivities.isEmpty
currentActivityButton?.tintColor = hasCurrentActivity ? Assets.Colors.primaryAccent : .label
}
override func viewWillAppear(_ animated: Bool) {
Self.logger.debug("MainFeedCollectionViewController: viewWillAppear")
navigationController?.isToolbarHidden = false
configureToolbarWithProgressView()
updateUI()
super.viewWillAppear(animated)
if traitCollection.userInterfaceIdiom == .phone {
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .always
DispatchQueue.main.async {
// Sizes the bar to large. Skip if a pushed VC (e.g. the timeline, which shares this bar
// on iPhone) is now on top, or it would be forced large too.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5141>
guard self.navigationController?.topViewController === self else {
return
}
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
}
// Rotating a Pro Max to landscape expands the split view — wait for the transition to settle.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5043>
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// Deselect only when the feeds list is full screen.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4691>
if self.coordinator.isRootSplitCollapsed, self.collectionView.indexPathsForSelectedItems?.first != nil {
self.coordinator.selectSidebarItem(indexPath: nil, animations: [.select])
}
}
}
func registerForNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleFeedIconImageDidChange(_:)), name: .feedIconImageDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleGrayscaleIconsDidChange(_:)), name: .grayscaleIconsDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(feedSettingDidChange(_:)), name: .feedSettingDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDisplaySettingDidChange(_:)), name: .unreadCountDisplaySettingDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleSidebarShowsIconsDidChange(_:)), name: .sidebarShowsIconsDidChange, 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 = { [weak self] indexPath in
guard let self else {
return nil
}
// The smart feeds section has an empty identifier. It’s absent when every smart feed is hidden.
if let sectionID = self.dataSource.sectionIdentifier(for: indexPath.section), sectionID.isEmpty {
return UISwipeActionsConfiguration(actions: [])
}
var actions = [UIContextualAction]()
// Set up the delete action
let deleteTitle = NSLocalizedString("Delete", comment: "Delete button")
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: "Command")
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)
}
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel button")
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
} else {
collectionView.backgroundColor = .systemGroupedBackground
}
}
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.setDisclosure(isExpanded: self.coordinator.isExpanded(SmartFeedsController.shared), animated: false)
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.setDisclosure(isExpanded: self.coordinator.isExpanded(account), animated: false)
headerView.addInteraction(UIContextMenuInteraction(delegate: self))
return headerView
}
}
func applySnapshot(_ snapshot: NSDiffableDataSourceSnapshot<String, SidebarItemNode>, animatingDifferences: Bool, completion: (() -> Void)? = nil) {
let feeds = snapshot.itemIdentifiers.compactMap { $0.node.representedObject as? Feed }
IconImageCache.shared.prefetchImagesForFeeds(feeds)
enqueueSidebarUpdate(.full(snapshot, animated: animatingDifferences), completion: completion)
}
func reconfigureItems(_ items: [SidebarItemNode], completion: (() -> Void)? = nil) {
enqueueSidebarUpdate(.reconfigure(items), completion: completion)
}
// MARK: - Data Source Queries
var currentSidebarSnapshot: NSDiffableDataSourceSnapshot<String, SidebarItemNode> {
dataSource.snapshot()
}
func sidebarItemNode(for indexPath: IndexPath) -> SidebarItemNode? {
dataSource.itemIdentifier(for: indexPath)
}
func indexPath(for sidebarItemNode: SidebarItemNode) -> IndexPath? {
dataSource.indexPath(for: sidebarItemNode)
}
// MARK: - Serialized Snapshot Updates
// Overlapping animated dataSource.apply calls strand cells — a row mid-delete-animation
// never gets recycled while the next update slides another row into its slot, leaving
// two cells overlapping. Updates are queued and applied one at a time. The apply
// completion is the animation-end signal, so serializing on it is sufficient.
private func enqueueSidebarUpdate(_ update: SidebarUpdate, completion: (() -> Void)?) {
var completions = [() -> Void]()
if let completion {
completions.append(completion)
}
// A newer full snapshot supersedes a queued one. The superseded update’s
// completions still run — after a snapshot at least as new as the one they requested.
if update.isFull, let index = queuedSidebarUpdates.firstIndex(where: { $0.update.isFull }) {
completions = queuedSidebarUpdates[index].completions + completions
queuedSidebarUpdates.remove(at: index)
}
queuedSidebarUpdates.append(QueuedSidebarUpdate(update: update, completions: completions))
applyNextSidebarUpdateIfPossible()
}
private func applyNextSidebarUpdateIfPossible() {
guard !isApplyingSnapshot, !queuedSidebarUpdates.isEmpty else {
return
}
let queuedUpdate = queuedSidebarUpdates.removeFirst()
var snapshot: NSDiffableDataSourceSnapshot<String, SidebarItemNode>
var animated = false
switch queuedUpdate.update {
case .full(let fullSnapshot, let fullAnimated):
snapshot = fullSnapshot
animated = fullAnimated
case .reconfigure(let items):
snapshot = dataSource.snapshot()
let survivingItems = survivingItems(items, in: snapshot)
guard !survivingItems.isEmpty else {
finishSkippedSidebarUpdate(queuedUpdate)
return
}
snapshot.reconfigureItems(survivingItems)
case .reload(let items):
snapshot = dataSource.snapshot()
let survivingItems = survivingItems(items, in: snapshot)
guard !survivingItems.isEmpty else {
finishSkippedSidebarUpdate(queuedUpdate)
return
}
snapshot.reloadItems(survivingItems)
}
// Animating a batch update while detached from a window strands cells too.
let animatingDifferences = animated && viewIfLoaded?.window != nil
isApplyingSnapshot = true
dataSource.apply(snapshot, animatingDifferences: animatingDifferences) { [weak self] in
guard let self else {
return
}
// Completions run before the queue pumps again, so an update enqueued
// synchronously by a completion applies after this one — in order.
for completion in queuedUpdate.completions {
completion()
}
self.isApplyingSnapshot = false
self.applyNextSidebarUpdateIfPossible()
}
}
// Reconfigures and reloads resolve their items at execution time, against the
// currently applied snapshot. Items removed by an earlier queued update are
// skipped — reloading an absent identifier throws.
private func survivingItems(_ items: [SidebarItemNode], in snapshot: NSDiffableDataSourceSnapshot<String, SidebarItemNode>) -> [SidebarItemNode] {
let currentItems = Set(snapshot.itemIdentifiers)
return items.filter { currentItems.contains($0) }
}
private func finishSkippedSidebarUpdate(_ queuedUpdate: QueuedSidebarUpdate) {
for completion in queuedUpdate.completions {
completion()
}
applyNextSidebarUpdateIfPossible()
}
@IBAction func settings(_ sender: UIBarButtonItem) {
coordinator.showSettings()
}
@objc func showCurrentActivity(_ sender: Any?) {
coordinator.showCurrentActivity()
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
becomeFirstResponder()
}
// Fires on every tap — even on the already-selected feed, which doesn’t get didSelectItemAt.
override func collectionView(_ collectionView: UICollectionView, performPrimaryActionForItemAt indexPath: IndexPath) {
becomeFirstResponder()
coordinator.selectSidebarItem(indexPath: indexPath, animations: [.navigation, .select, .scroll])
}
override func collectionView(_ collectionView: UICollectionView, canPerformPrimaryActionForItemAt indexPath: IndexPath) -> Bool {
if traitCollection.userInterfaceIdiom == .pad {
return true
}
return !isAnimating
}
// 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.setDisclosure(isExpanded: false, animated: true)
}
}
}
@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.setDisclosure(isExpanded: true, animated: 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: "Command")
let articlesToMark = coordinator.articles
MarkAsReadAlertController.confirm(self, confirmTitle: title, sourceType: contentView) { [weak self] in
self?.coordinator.markAsReadAndShowSidebar(articlesToMark)
}
}
@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) {
guard let vc = SFSafariViewController.safeSafariViewController(url) else {
return
}
// Apply the resolved userInterfaceStyle before presenting to avoid a white flash in dark mode.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5383>
vc.overrideUserInterfaceStyle = traitCollection.userInterfaceStyle
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 splitViewStateDidChange() {
updateVisibleCellConfigurations()
}
private func updateVisibleCellConfigurations() {
guard isViewLoaded, let collectionView else {
return
}
for cell in collectionView.visibleCells {
cell.setNeedsUpdateConfiguration()
}
}
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: [])
}
}
}
// MARK: - Private
func configureToolbarWithProgressView() {
if #available(iOS 26, *) {
return
}
guard !isToolbarConfigured else {
return
}
// Expect three items: left button, flex space, right button.
let expectedItemCount = 3
guard var items = toolbarItems, items.count == expectedItemCount else {
return
}
// Replace the middle flex space with: flex, progress, flex
// to center the progress view between the two buttons.
let middleIndex = 1
isToolbarConfigured = true
let refreshBarItem = UIBarButtonItem(customView: refreshProgressView)
items[middleIndex] = UIBarButtonItem.flexibleSpace()
items.insert(refreshBarItem, at: middleIndex + 1)
items.insert(UIBarButtonItem.flexibleSpace(), at: middleIndex + 2)
toolbarItems = items
}
/// 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
cell.showsIcon = AppDefaults.sidebarShowsIcons
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
cell.showsIcon = AppDefaults.sidebarShowsIcons
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
}
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
}
enqueueSidebarUpdate(.reload(items), completion: completion)
}
func setFilterButtonToActive() {
filterButton.tintColor = Assets.Colors.primaryAccent
filterButton?.accLabelText = NSLocalizedString("Selected - Filter Read Feeds", comment: "Selected - Filter Read Feeds")
}
func setFilterButtonToInactive() {
filterButton.tintColor = .label
filterButton?.accLabelText = NSLocalizedString("Filter Read Feeds", comment: "Filter Read Feeds")
}
// MARK: - Notifications
@objc func preferredContentSizeCategoryDidChange() {
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
}
// Reconfigure through the serialized funnel — mutating visible cells directly
// can change their size in the middle of an animated snapshot apply.
let nodesToReconfigure = dataSource.snapshot().itemIdentifiers.filter {
$0.node.representedObject === unreadCountProvider as AnyObject
}
guard !nodesToReconfigure.isEmpty else {
return
}
reconfigureItems(nodesToReconfigure)
}
@objc func handleUnreadCountDisplaySettingDidChange(_ notification: Notification) {
for account in AccountManager.shared.activeAccounts {
if let headerView = findHeaderViewForAccount(account) {
headerView.unreadCount = account.unreadCount
}
}
// Only realized cells are reconfigured. Others pick up the setting when dequeued.
reconfigureItems(dataSource.snapshot().itemIdentifiers)
}
@objc func handleSidebarShowsIconsDidChange(_ notification: Notification) {
// Only realized cells are reconfigured. Others pick up the setting when dequeued.
reconfigureItems(dataSource.snapshot().itemIdentifiers)
}
@objc func handleGrayscaleIconsDidChange(_ notification: Notification) {
// Only realized cells are reconfigured. Others pick up the setting when dequeued.
reconfigureItems(dataSource.snapshot().itemIdentifiers)
}
@objc func feedSettingDidChange(_ note: Notification) {
guard let feed = note.object as? Feed, let key = note.userInfo?[Feed.SettingUserInfoKey] as? Feed.SettingKey else {
return
}
if key == .homePageURL || key == .faviconURL {
configureCellsForRepresentedObject(feed)
}
}
@objc func handleFeedIconImageDidChange(_ notification: Notification) {
guard let feed = notification.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: "", 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 alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel button")
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()
}
alertController.addAction(addFeedAction)
let anyActiveAccountSupportsFolders: Bool = {
for account in AccountManager.shared.activeAccounts {
if !account.behaviors.contains(.disallowFolderManagement) {
return true
}
}
return false
}()
if anyActiveAccountSupportsFolders {
let addFolderActionTitle = NSLocalizedString("Add Folder", comment: "Add Folder")
let addFolderAction = UIAlertAction(title: addFolderActionTitle, style: .default) { _ in
self.coordinator.showAddFolder()
}
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.setDisclosure(isExpanded: false, animated: true)
coordinator.collapse(containerID)
} else {
headerView.setDisclosure(isExpanded: true, animated: 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)]))
menuElements.append(UIMenu(title: "", options: .displayInline, children: [self.getAccountNotificationsAction(account: account)]))
if let markAllAction = self.markAllAsReadAction(account: account, contentView: interaction.view) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [markAllAction]))
}
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 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]))
}
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? {
guard let markAllAction = self.markAllAsReadAction(indexPath: indexPath) else {
return nil
}
return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { _ in
return UIMenu(title: "", children: [markAllAction])
})
}
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: "Command")
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? {
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: "Command")
let action = UIAlertAction(title: title, style: .default) { _ in
UIApplication.shared.open(url, options: [:])
completion(true)
}
return action
}
func copyFeedPageAction(indexPath: IndexPath) -> UIAction? {
guard let feed = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? Feed,
let url = URL(string: feed.url) else {
return nil
}
let title = NSLocalizedString("Copy Feed URL", comment: "Command")
let action = UIAction(title: title, image: Assets.Images.copy) { _ in
UIPasteboard.general.url = url
}
return action
}
func copyFeedPageAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? {
guard let feed = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? Feed,
let url = URL(string: feed.url) else {
return nil
}
let title = NSLocalizedString("Copy Feed URL", comment: "Command")
let action = UIAlertAction(title: title, style: .default) { _ in
UIPasteboard.general.url = url
completion(true)
}
return action
}
func copyHomePageAction(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("Copy Home Page URL", comment: "Command")
let action = UIAction(title: title, image: Assets.Images.copy) { _ in
UIPasteboard.general.url = url
}
return action
}
func copyHomePageAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? {
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("Copy Home Page URL", comment: "Command")
let action = UIAlertAction(title: title, style: .default) { _ in
UIPasteboard.general.url = url
completion(true)
}
return action
}
func markAllAsReadAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? {
guard let feed = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? Feed,
feed.unreadCount > 0 else {
return nil
}
guard let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else {
return nil
}
let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command")
let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String
let cancel = {
completion(true)
}
let action = UIAlertAction(title: title, style: .default) { [weak self] _ in
MarkAsReadAlertController.confirm(self, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in
let articles = feed.fetchUnreadArticles()
self?.coordinator.markAllAsRead(Array(articles), in: feed)
completion(true)
}
}
return action
}
func deleteAction(indexPath: IndexPath) -> UIAction {
let title = NSLocalizedString("Delete", comment: "Delete button")
let action = UIAction(title: title, image: Assets.Images.trash, attributes: .destructive) { [weak self] _ in
self?.delete(indexPath: indexPath)
}
return action
}
func renameAction(indexPath: IndexPath) -> UIAction {
let title = NSLocalizedString("Rename", comment: "Command")
let action = UIAction(title: title, image: Assets.Images.edit) { [weak self] _ in
self?.rename(indexPath: indexPath)
}
return action
}
func getInfoAction(indexPath: IndexPath) -> UIAction? {
guard let feed = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? Feed else {
return nil
}
let title = NSLocalizedString("Get Info", comment: "Get Info")
let action = UIAction(title: title, image: Assets.Images.info) { [weak self] _ in
self?.coordinator.showFeedInspector(for: feed)
}
return action
}
func getAccountInfoAction(account: Account) -> UIAction {
let title = NSLocalizedString("Get Info", comment: "Get Info")
let action = UIAction(title: title, image: Assets.Images.info) { [weak self] _ in
self?.coordinator.showAccountInspector(for: account)
}
return action
}
func getAccountNotificationsAction(account: Account) -> UIAction {
let title = NSLocalizedString("Notifications", comment: "Notifications")
let action = UIAction(title: title, image: UIImage(systemName: "bell.badge")) { [weak self] _ in
self?.coordinator.showNotificationInspector(for: account)
}
return action
}
func deactivateAccountAction(account: Account) -> UIAction {
let title = NSLocalizedString("Deactivate", comment: "Deactivate")
let action = UIAction(title: title, image: Assets.Images.deactivate) { _ in
account.isActive = false
}
return action
}
func getInfoAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? {
guard let feed = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? Feed else {
return nil
}
let title = NSLocalizedString("Get Info", comment: "Get Info")
let action = UIAlertAction(title: title, style: .default) { [weak self] _ in
self?.coordinator.showFeedInspector(for: feed)
completion(true)
}
return action
}
func markAllAsReadAction(indexPath: IndexPath) -> UIAction? {
guard let sidebarItem = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? SidebarItem,
let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView,
sidebarItem.unreadCount > 0 else {
return nil
}
let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command")
let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, sidebarItem.nameForDisplay) as String
let action = UIAction(title: title, image: Assets.Images.markAllAsRead) { [weak self] _ in
MarkAsReadAlertController.confirm(self, confirmTitle: title, sourceType: contentView) { [weak self] in
let articles = sidebarItem.fetchUnreadArticles()
self?.coordinator.markAllAsRead(Array(articles), in: sidebarItem)
}
}
return action
}
func markAllAsReadAction(account: Account, contentView: UIView?) -> UIAction? {
guard account.unreadCount > 0, let contentView else {
return nil
}
let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command")
let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, account.nameForDisplay) as String
let action = UIAction(title: title, image: Assets.Images.markAllAsRead) { [weak self] _ in
MarkAsReadAlertController.confirm(self, confirmTitle: title, sourceType: contentView) { [weak self] in
// If you don’t have this delay the screen flashes when it executes this code
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
let articles = account.fetchArticles(.unread())
self?.coordinator.markAllAsRead(Array(articles))
}
}
}
return action
}
func rename(indexPath: IndexPath) {
guard let sidebarItem = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? SidebarItem else {
return
}
let formatString = NSLocalizedString("Rename “%@”", comment: "Rename feed")
let title = NSString.localizedStringWithFormat(formatString as NSString, sidebarItem.nameForDisplay) as String
let alertController = UIAlertController(title: title, message: nil, preferredStyle: .alert)
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel button")
alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel))
let renameTitle = NSLocalizedString("Rename", comment: "Command")
let renameAction = UIAlertAction(title: renameTitle, style: .default) { [weak self] _ in
guard let name = alertController.textFields?[0].text, !name.isEmpty else {
return
}
if let feed = sidebarItem as? Feed {
feed.rename(to: name) { result in
switch result {
case .success:
break
case .failure(let error):
self?.presentError(error)
}
}
} else if let folder = sidebarItem as? Folder {
folder.rename(to: name) { result in
switch result {
case .success:
break
case .failure(let error):
self?.presentError(error)
}
}
}
}
alertController.addAction(renameAction)
alertController.preferredAction = renameAction
alertController.addTextField { textField in
textField.text = sidebarItem.nameForDisplay
textField.placeholder = NSLocalizedString("Name", comment: "Name field placeholder")
textField.clearButtonMode = .always
}
self.present(alertController, animated: true) {
}
}
func delete(indexPath: IndexPath) {
guard let sidebarItem = dataSource.itemIdentifier(for: indexPath)?.node.representedObject as? SidebarItem else {
return
}
let title: String
let message: String
if sidebarItem is Folder {
title = NSLocalizedString("Delete Folder", comment: "Command")
let localizedInformativeText = NSLocalizedString("Are you sure you want to delete the “%@” folder?", comment: "Folder delete text")
message = NSString.localizedStringWithFormat(localizedInformativeText as NSString, sidebarItem.nameForDisplay) as String
} else {
title = NSLocalizedString("Delete Feed", comment: "Delete Feed")
let localizedInformativeText = NSLocalizedString("Are you sure you want to delete the “%@” feed?", comment: "Feed delete text")
message = NSString.localizedStringWithFormat(localizedInformativeText as NSString, sidebarItem.nameForDisplay) as String
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel button")
alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel))
let deleteTitle = NSLocalizedString("Delete", comment: "Delete button")
let deleteAction = UIAlertAction(title: deleteTitle, style: .destructive) { [weak self] _ in
self?.performDelete(indexPath: indexPath)
}
alertController.addAction(deleteAction)
alertController.preferredAction = deleteAction
self.present(alertController, animated: true)
}
func performDelete(indexPath: IndexPath) {
guard let undoManager = undoManager,
let deleteNode = dataSource.itemIdentifier(for: indexPath)?.node,
let deleteCommand = DeleteCommand(nodesToDelete: [deleteNode], undoManager: undoManager, errorHandler: ErrorHandler.present(self)) else {
return
}
if let folder = deleteNode.representedObject as? Folder {
ActivityManager.cleanUp(folder)
} else if let feed = deleteNode.representedObject as? Feed {
ActivityManager.cleanUp(feed)
}
if indexPath == coordinator.currentFeedIndexPath {
coordinator.selectSidebarItem(indexPath: nil)
}
pushUndoableCommand(deleteCommand)
deleteCommand.perform()
}
}
// MARK: - SidebarUpdate
private enum SidebarUpdate {
case full(NSDiffableDataSourceSnapshot<String, SidebarItemNode>, animated: Bool)
case reconfigure([SidebarItemNode])
case reload([SidebarItemNode])
var isFull: Bool {
if case .full = self {
return true
}
return false
}
}
private struct QueuedSidebarUpdate {
let update: SidebarUpdate
let completions: [() -> Void]
}