// // MainTimelineViewController.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 HTMLMetadata import Account import Articles import Images final class MainTimelineViewController: UIViewController, UndoableCommandRunner { // MARK: Private Variables private var numberOfTextLines = 0 private var iconSize = IconSize.medium private var thumbnailsDisplay = TimelineThumbnailsDisplay.none private var fadesReadArticles = false private var feedNameAndDateAboveTitle = false private var showsFullTitles = false private var articleIDsToReload = Set() private var markReadBehavior = AppDefaults.markReadBehavior { didSet { if markReadBehavior != oldValue { updateNextUnreadFooter() invalidateLayoutForNextUnreadFooter() noteRowsScrolledPast() } } } /// Rows under the navigation bar or above it at the last check. Rows past this count are newly scrolled past. private var rowCountScrolledPast = 0 /// An article is marked read on scroll only once, so one the user marks unread again stays unread. private var articlesMarkedReadOnScroll = Set() private var articlesPendingMarkReadOnScroll = [Article]() /// Shown in the footer after the last row. Nil hides the footer’s button. private var nextSidebarItemWithUnreadArticles: SidebarItem? /// When marking read on scroll, the footer after the last row is as tall as the area between the navigation bar and the toolbar, so every row can scroll under the navigation bar. private var scrolledPastFooterHeight: CGFloat = 0 /// The article whose row was just swiped to change its status. private var swipedArticleID: String? 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 nextUnreadButton = UIBarButtonItem(image: Assets.Images.nextUnread, style: .plain, target: self, action: #selector(nextUnread(_:))) private let refreshProgressView = RefreshProgressView(frame: .zero) private lazy var refreshBarItem = UIBarButtonItem(customView: refreshProgressView) private var isToolbarProgressViewShowing = false private var dataSource: UICollectionViewDiffableDataSource? var didPushArticleViewController = false private var timelineFeed: SidebarItem? { assert(coordinator != nil) return coordinator?.timelineFeed } private var showIcons: Bool { assert(coordinator != nil) return coordinator?.showIcons ?? false } /// Nil when the timeline doesn’t show thumbnails. private var thumbnailMode: ThumbnailMode? { thumbnailsDisplay.thumbnailMode } private var currentArticle: Article? { assert(coordinator != nil) return coordinator?.currentArticle } 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 func isSidebarHidden(for displayMode: UISplitViewController.DisplayMode? = nil) -> Bool { if isRootSplitCollapsed { return true } let mode = displayMode ?? splitViewController?.displayMode ?? .automatic // Sidebar is hidden only in these specific modes let sidebarHidden = mode == .secondaryOnly || mode == .oneBesideSecondary || mode == .oneOverSecondary return sidebarHidden } 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) label.text = Self.navigationBarPlaceholderText label.sizeToFit() return label }() private lazy var navigationBarSubtitleTitleLabel: UILabel = { let label = UILabel() label.font = .systemFont(ofSize: 12) label.textColor = .systemGray label.textAlignment = .center label.isUserInteractionEnabled = true label.adjustsFontForContentSizeCategory = false let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) label.addGestureRecognizer(tap) label.text = Self.navigationBarPlaceholderText label.sizeToFit() return label }() // MARK: Variables weak var coordinator: SceneCoordinator? var undoableCommands = [UndoableCommand]() override var keyCommands: [UIKeyCommand]? { // If the first responder is the WKWebView (ArticleWebView) 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 ArticleWebView) else { return nil } return keyboardManager.keyCommands } override var canBecomeFirstResponder: Bool { true } // The selected row is accent-colored only while the timeline 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 } // MARK: Private Constants private let searchController = UISearchController(searchResultsController: nil) private let keyboardManager = KeyboardManager(type: .timeline) private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "MainTimelineViewController") /// Cells queued within this interval, such as for several thumbnail downloads that failed, are reloaded together. private static let cellReloadDelay: TimeInterval = 0.1 /// A zero-width titleView or subtitleView crashes UINavigationBar layout, so labels whose text measures zero width (empty, or only a combining mark) get a space instead. /// private static let navigationBarPlaceholderText = " " /// Marking waits for a pause in scrolling, so one Undo restores what one stretch of scrolling marked. private static let markReadOnScrollDelay: TimeInterval = 0.5 /// How much of a row must be under the navigation bar or above it to count as scrolled past. private static let scrolledPastFraction: CGFloat = 0.75 // MARK: Constants 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.timelineNumberOfLines iconSize = AppDefaults.timelineIconSize thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay fadesReadArticles = AppDefaults.timelineFadeReadArticles feedNameAndDateAboveTitle = AppDefaults.timelineFeedNameAndDateAboveTitle showsFullTitles = AppDefaults.timelineShowFullTitles assert(collectionView?.refreshControl != nil) collectionView?.refreshControl = UIRefreshControl() collectionView?.refreshControl?.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) configureToolbar() resetUI(resetScroll: true) applyChanges(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 if #available(iOS 26, *) { navigationItem.subtitleView = navigationBarSubtitleTitleLabel } // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateToolbarProgressView() updateNextUnreadFooterHeight() coordinator?.timelineDidLayout() } override func viewWillAppear(_ animated: Bool) { Self.logger.debug("MainTimelineViewController: 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 } // Re-assert small title in case the shared iPhone nav bar was left in large mode. // navigationItem.largeTitleDisplayMode = .never updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "") coordinator?.updateNavigationBarSubtitles(nil) updateToolbarProgressView() // Articles can change while this view is off screen, so always show what the model holds. applyChanges(animated: false) } override func viewDidAppear(_ animated: Bool) { Self.logger.debug("MainTimelineViewController: viewDidAppear") super.viewDidAppear(animated) isTimelineViewControllerPending = false if navigationController?.navigationBar.alpha == 0 { UIView.animate(withDuration: 0.5) { self.navigationController?.navigationBar.alpha = 1 } } // Deselect only when returning from article navigation, and not while // another article push is in flight. // if let coordinator, coordinator.isRootSplitCollapsed, didPushArticleViewController, !coordinator.isArticleViewControllerPending { didPushArticleViewController = false self.deselectIfNecessary() } } func deselectIfNecessary() { Self.logger.debug("MainTimelineViewController: deselectIfNecessary") guard traitCollection.userInterfaceIdiom == .phone else { return } guard let coordinator, coordinator.isRootSplitCollapsed else { return } if coordinator.currentArticle != nil { Self.logger.debug("MainTimelineViewController: deselectIfNecessary deselecting") if let indexPath = collectionView?.indexPathsForSelectedItems?.first { collectionView?.deselectItem(at: indexPath, animated: true) } coordinator.selectArticle(nil) } } func restoreSelectionIfNecessary(adjustScroll: Bool) { Self.logger.debug("MainTimelineViewController: restoreSelectionIfNecessary") guard let collectionView else { return } if let article = currentArticle, let dataSource, let indexPath = dataSource.indexPath(for: article) { if adjustScroll { Self.logger.debug("MainTimelineViewController: restoreSelectionIfNecessary selecting item and adjusting scroll") collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: []) } else { let indexPaths = collectionView.indexPathsForSelectedItems ?? [] if !indexPaths.contains(indexPath) { Self.logger.debug("MainTimelineViewController: restoreSelectionIfNecessary does not contain selected index path") collectionView.selectItem(at: indexPath, animated: false, scrollPosition: []) } } } } func updateNavigationBarTitle(_ text: String) { navigationItem.title = text if let label = navigationItem.titleView as? UILabel { label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) setNavigationBarLabelText(label, text) } } func updateNavigationBarSubtitle(_ text: String) { if #available(iOS 26, *), let label = navigationItem.subtitleView as? UILabel { label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) setNavigationBarLabelText(label, text) } } private func setNavigationBarLabelText(_ label: UILabel, _ text: String) { label.text = text label.sizeToFit() if !(label.bounds.width > 0) { label.text = Self.navigationBarPlaceholderText label.sizeToFit() } } func reinitializeArticles(resetScroll: Bool) { Self.logger.debug("MainTimelineViewController: reinitializeArticles") guard isViewLoaded else { return } if resetScroll { articlesMarkedReadOnScroll.removeAll() } resetUI(resetScroll: resetScroll) restoreSelectionIfNecessary(adjustScroll: false) updateNextUnreadFooter() noteRowsScrolledPast() } func reloadArticles(animated: Bool) { Self.logger.debug("MainTimelineViewController: reloadArticles") guard isViewLoaded else { return } applyChanges(animated: animated) } func updateArticleSelection(animations: Animations) { Self.logger.debug("MainTimelineViewController: 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("MainTimelineViewController: updateUI") updateToolbar() updateNextUnreadFooter() } func hideSearch(completion: (() -> Void)? = nil) { guard let searchController = navigationItem.searchController, searchController.isActive else { completion?() return } searchController.isActive = false guard let transitionCoordinator = searchController.transitionCoordinator else { completion?() return } transitionCoordinator.animate(alongsideTransition: nil) { _ in completion?() } } func showSearchAll() { navigationItem.searchController?.isActive = true navigationItem.searchController?.searchBar.selectedScopeButtonIndex = 1 navigationItem.searchController?.searchBar.becomeFirstResponder() } func focus() { Self.logger.debug("MainTimelineViewController: focus") becomeFirstResponder() } // MARK: - Reloading func queueReloadAvailableCells() { updateQueue.add(self, #selector(reloadVisibleCells)) } /// Icons arrive in bursts, so the reload is still coalesced. private func queueReloadIfVisibleArticleMightShowIcon(in notification: Notification) { guard isViewLoaded, showIcons, visibleArticles().contains(where: { $0.mightShowIcon(in: notification) }) else { return } queueReloadAvailableCells() } @objc private func reloadVisibleCells() { Self.logger.debug("MainTimelineViewController: reloadVisibleCells") guard isViewLoaded, let collectionView, let dataSource else { return } let indexPaths = collectionView.indexPathsForVisibleItems let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } reloadCells(visibleArticles) } /// Measures every row again, including rows that aren’t visible. func reloadAllCells() { guard let dataSource else { return } dataSource.applySnapshotUsingReloadData(dataSource.snapshot()) { [weak self] in self?.restoreSelectionIfNecessary(adjustScroll: true) } } /// Reloads after `cellReloadDelay`, together with any other cells queued by then. private func reloadCells(_ articles: [Article]) { guard !articles.isEmpty else { return } let isReloadScheduled = !articleIDsToReload.isEmpty articleIDsToReload.formUnion(articles.map(\.articleID)) guard !isReloadScheduled else { return } DispatchQueue.main.asyncAfter(deadline: .now() + Self.cellReloadDelay) { self.reloadQueuedCells() } } /// Uses the current snapshot, so articles that changed or left the timeline since being queued are handled. private func reloadQueuedCells() { Self.logger.debug("MainTimelineViewController: reloadQueuedCells") let articleIDs = articleIDsToReload articleIDsToReload.removeAll() guard let dataSource else { return } var snapshot = dataSource.snapshot() let articlesToReload = snapshot.itemIdentifiers.filter { articleIDs.contains($0.articleID) } guard !articlesToReload.isEmpty else { return } snapshot.reconfigureItems(articlesToReload) 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() } @IBAction func markAllAsRead(_ sender: Any?) { guard let coordinator else { assertionFailure("Expected coordinator") return } let title = NSLocalizedString("Mark All as Read", comment: "Command") let articlesToMark = coordinator.articles if let source = sender as? UIBarButtonItem { MarkAsReadAlertController.confirm(self, confirmTitle: title, sourceType: source) { [weak self] in self?.coordinator?.markAsReadAndShowSidebar(articlesToMark) } } 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, confirmTitle: title, sourceType: contentView) { [weak self] in self?.coordinator?.markAsReadAndShowSidebar(articlesToMark) } } } @IBAction func nextUnread(_ sender: Any) { assert(coordinator != nil) coordinator?.selectNextUnread() } /* // 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 MainTimelineViewController: 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]) } } /// The navigation bar’s and toolbar’s heights can change. func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) { updateNextUnreadFooterHeight() } func scrollViewDidScroll(_ scrollView: UIScrollView) { guard markReadBehavior == .selectionAndScrolledPast else { return } if scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating { markRowsScrolledPastAsRead() } else { noteRowsScrolledPast() } } /// Cells are configured before they’re displayed, and thumbnail notifications update only visible cells. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let thumbnailMode, let cell = cell as? MainTimelineCell, let cellData = cell.cellData, let article = dataSource?.itemIdentifier(for: indexPath) else { return } let thumbnailURL = ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) if (thumbnailURL != nil) != cellData.showThumbnail { // The row’s height changes too. reloadCells([article]) return } guard let thumbnailURL, let thumbnail = ThumbnailDownloader.shared.thumbnail(url: thumbnailURL, mode: thumbnailMode, feedName: article.feed?.nameForDisplay, articleTitle: article.title), thumbnail !== cell.thumbnail else { return } cell.thumbnail = thumbnail } 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 } // The preview is off by default, since it can cover part of the menu. var previewProvider: UIContextMenuContentPreviewProvider? if AppDefaults.showPreviewInTimelineContextMenu { previewProvider = { [weak self] in guard let coordinator = self?.coordinator else { return nil } return ArticlePreviewViewController(article: article, coordinator: coordinator) } } return UIContextMenuConfiguration(identifier: firstIndex.row as NSCopying, previewProvider: previewProvider, 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 !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, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: any UIContextMenuInteractionCommitAnimating) { // The timeline may have changed since the menu opened, so use the previewed article, not the row. guard let articlePreviewViewController = animator.previewViewController as? ArticlePreviewViewController else { return } let article = articlePreviewViewController.article animator.addCompletion { [weak self] in self?.coordinator?.selectArticle(article, animations: [.scroll, .select, .navigation]) } } 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)), cell.window != nil 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)), cell.window != nil 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: - Toolbar Progress View extension MainTimelineViewController { func updateToolbarProgressView(for displayMode: UISplitViewController.DisplayMode? = nil) { if #available(iOS 26, *) { return } isToolbarProgressViewShowing = isSidebarHidden(for: displayMode) rebuildToolbarItems() } } // MARK: - Split View State extension MainTimelineViewController { /// The selection style — full-bleed gray when collapsed, rounded accent when /// expanded — depends on the split view state, so visible cells need a refresh /// when it changes. func splitViewStateDidChange() { updateVisibleCellConfigurations() } } // MARK: Private API private extension MainTimelineViewController { func updateVisibleCellConfigurations() { guard isViewLoaded, let collectionView else { return } for cell in collectionView.visibleCells { cell.setNeedsUpdateConfiguration() } } 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(handleFeedIconImageDidChange(_:)), name: .feedIconImageDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleGrayscaleIconsDidChange(_:)), name: .grayscaleIconsDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleAuthorAvatarImageDidChange(_:)), name: .authorAvatarImageDidChange, 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(handleTimelineThumbnailsDisplayDidChange(_:)), name: .timelineThumbnailsDisplayDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFadeReadArticlesDidChange(_:)), name: .timelineFadeReadArticlesDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleMarkReadBehaviorDidChange(_:)), name: .markReadBehaviorDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDisplaySettingDidChange(_:)), name: .unreadCountDisplaySettingDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineFeedNameAndDateAboveTitleDidChange(_:)), name: .timelineFeedNameAndDateAboveTitleDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleTimelineShowFullTitlesDidChange(_:)), name: .timelineShowFullTitlesDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleThumbnailDidBecomeAvailable(_:)), name: .thumbnailDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleArticleThumbnailDownloadDidFail(_:)), name: .articleThumbnailDownloadDidFail, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleNetworkStatusDidChange(_:)), name: .networkStatusDidChange, 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) NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, 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 if #available(iOS 26, *) { navigationItem.searchBarPlacementAllowsExternalIntegration = true } } } private func configureCollectionView(_ dataSource: UICollectionViewDiffableDataSource) { var config = UICollectionLayoutListConfiguration(appearance: .plain) config.headerMode = .none config.footerMode = .supplementary // System separators between rows, none above the first row or below the last. Each cell lines its separator up with its text. config.itemSeparatorHandler = { [weak self] indexPath, sectionSeparatorConfiguration in var separatorConfiguration = sectionSeparatorConfiguration separatorConfiguration.topSeparatorVisibility = .hidden if let collectionView = self?.collectionView, indexPath.item == collectionView.numberOfItems(inSection: indexPath.section) - 1 { separatorConfiguration.bottomSeparatorVisibility = .hidden } return separatorConfiguration } config.trailingSwipeActionsConfigurationProvider = { [weak self] indexPath in guard let self else { return nil } 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 // Post the accessibility announcement immediately so VoiceOver // doesn’t lag behind user actions. let announcement = article.status.starred ? NSLocalizedString("Unstarred", comment: "Accessibility announcement") : NSLocalizedString("Starred", comment: "Starred") UIAccessibility.post(notification: .announcement, argument: announcement) self?.swipedArticleID = article.articleID 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.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 button") 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 = { [weak self] indexPath in guard let self else { return nil } 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: "Command") : NSLocalizedString("Mark as Read", comment: "Command") let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] _, _, completion in // Post the accessibility announcement immediately so VoiceOver // doesn’t lag behind user actions. let announcement = article.status.read ? NSLocalizedString("Marked as Unread", comment: "Accessibility announcement") : NSLocalizedString("Marked as Read", comment: "Accessibility announcement") UIAccessibility.post(notification: .announcement, argument: announcement) self?.swipedArticleID = article.articleID 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) // Plain lists pin footers to the visible area. The footer belongs after the last row. for boundarySupplementaryItem in section.boundarySupplementaryItems { boundarySupplementaryItem.pinToVisibleBounds = false } /// Note to future self: apply insets that affect cell width /// calculations (leading swipe actions with sidebar visible) let sidebarOverlapWidth = layoutEnvironment.container.contentInsets.leading // container.contentSize includes the width under the sidebar. let remainingWidth = layoutEnvironment.container.contentSize.width - sidebarOverlapWidth section.contentInsets = NSDirectionalEdgeInsets( top: 0, leading: remainingWidth > 0 ? sidebarOverlapWidth : 0, bottom: 0, trailing: 0 ) return section } layout.configuration.contentInsetsReference = .safeArea collectionView?.collectionViewLayout = layout } private func makeDataSource(_ collectionView: UICollectionView) -> UICollectionViewDiffableDataSource { collectionView.register(MainTimelineCell.self, forCellWithReuseIdentifier: MainTimelineCell.reuseIdentifier) let dataSource: UICollectionViewDiffableDataSource = MainTimelineCollectionViewDataSource(collectionView: collectionView, cellProvider: { [weak self] collectionView, indexPath, article in guard let self else { return nil } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MainTimelineCell.reuseIdentifier, for: indexPath) as! MainTimelineCell cell.cellData = self.configure(article: article) return cell }) // UIKit requires creating the registration before the provider runs, not inside it. let nextUnreadFooterRegistration = UICollectionView.SupplementaryRegistration(elementKind: UICollectionView.elementKindSectionFooter) { [weak self] footerView, _, _ in self?.configureNextUnreadFooter(footerView) } dataSource.supplementaryViewProvider = { collectionView, _, indexPath in collectionView.dequeueConfiguredReusableSupplementary(using: nextUnreadFooterRegistration, for: indexPath) } return dataSource } @discardableResult private func configure(article: Article) -> MainTimelineCellData { let iconImage = iconImageFor(article) let showFeedNames = coordinator?.showFeedNames ?? ShowFeedName.none let showIcon = showIcons && iconImage != nil var thumbnail: UIImage? var showThumbnail = false if let thumbnailMode, let thumbnailURL = ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) { showThumbnail = true thumbnail = ThumbnailDownloader.shared.thumbnail(url: thumbnailURL, mode: thumbnailMode, feedName: article.feed?.nameForDisplay, articleTitle: article.title) } let cellData = MainTimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: iconImage, showIcon: showIcon, numberOfLines: numberOfTextLines, iconSize: iconSize, thumbnail: thumbnail, showThumbnail: showThumbnail, thumbnailsDisplay: thumbnailsDisplay, fadesReadArticles: fadesReadArticles, feedNameAndDateAboveTitle: feedNameAndDateAboveTitle, showsFullTitles: showsFullTitles) 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() { markAllAsReadButton?.image = Assets.Images.markAllAsRead if traitCollection.userInterfaceIdiom == .phone { if #available(iOS 26, *) { if let markAllAsRead = toolbarItems?.first { toolbarItems = [ markAllAsRead, .flexibleSpace(), navigationItem.searchBarPlacementBarButtonItem, .flexibleSpace(), nextUnreadButton ] } } else { // Remove storyboard placeholder flex spaces so rebuildToolbarItems starts clean. if let markAllAsRead = toolbarItems?.first { toolbarItems = [markAllAsRead] } } } updateToolbarProgressView() } func resetUI(resetScroll: Bool) { let shouldShowFilterButton = coordinator?.shouldShowFilterButton() ?? false navigationItem.rightBarButtonItem = shouldShowFilterButton ? filterButton : nil if isReadArticlesFiltered { filterButton.tintColor = Assets.Colors.primaryAccent filterButton.accLabelText = NSLocalizedString("Selected - Filter Read Articles", comment: "Selected - Filter Read Articles") } else { filterButton.tintColor = .label 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 nextUnreadButton.isEnabled = coordinator?.isNextUnreadAvailable ?? false if #unavailable(iOS 26) { rebuildToolbarItems() } } /// Rebuilds toolbar items from scratch based on current state. private func rebuildToolbarItems() { guard let markAllAsReadButton else { return } var items = [UIBarButtonItem]() items.append(markAllAsReadButton) if isToolbarProgressViewShowing { items.append(.flexibleSpace()) items.append(refreshBarItem) } items.append(.flexibleSpace()) items.append(nextUnreadButton) setToolbarItems(items, animated: false) } func applyChanges(animated: Bool, completion: (() -> Void)? = nil) { Self.logger.debug("MainTimelineViewController: applyChanges") guard let dataSource else { return } var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([0]) snapshot.appendItems(articles ?? ArticleArray(), toSection: 0) dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in self?.restoreSelectionIfNecessary(adjustScroll: false) self?.updateNextUnreadFooter() self?.noteRowsScrolledPast() completion?() } } } // MARK: - Mark Read on Scroll private extension MainTimelineViewController { /// Rows at least `scrolledPastFraction` under the navigation bar or above it. func numberOfRowsScrolledPast() -> Int { guard let collectionView else { return 0 } let visibleTop = collectionView.contentOffset.y + collectionView.adjustedContentInset.top guard visibleTop > 0 else { return 0 } let numberOfItems = collectionView.numberOfSections > 0 ? collectionView.numberOfItems(inSection: 0) : 0 guard let indexPath = collectionView.indexPathForItem(at: CGPoint(x: collectionView.bounds.midX, y: visibleTop)), let attributes = collectionView.layoutAttributesForItem(at: indexPath) else { // The top is past the last row, in the empty space after it. return numberOfItems } let rowFrame = attributes.frame let isScrolledPast = rowFrame.minY + rowFrame.height * Self.scrolledPastFraction <= visibleTop return isScrolledPast ? indexPath.item + 1 : indexPath.item } /// Records where the timeline is without marking anything — after a programmatic scroll or a change to the articles. func noteRowsScrolledPast() { guard markReadBehavior == .selectionAndScrolledPast else { return } rowCountScrolledPast = numberOfRowsScrolledPast() } /// Marks rows scrolled past since the last check. Scrolling up marks nothing. func markRowsScrolledPastAsRead() { let rowCount = numberOfRowsScrolledPast() defer { rowCountScrolledPast = rowCount } guard rowCount > rowCountScrolledPast, let dataSource else { return } for item in rowCountScrolledPast.. 0 else { return } for case let footerView as MainTimelineNextUnreadFooterView in collectionView.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionFooter) { footerView.minimumHeight = height } invalidateNextUnreadFooterSize() } func invalidateNextUnreadFooterSize() { guard let collectionView, collectionView.numberOfSections > 0 else { return } let context = UICollectionViewLayoutInvalidationContext() context.invalidateSupplementaryElements(ofKind: UICollectionView.elementKindSectionFooter, at: [IndexPath(item: 0, section: 0)]) collectionView.collectionViewLayout.invalidateLayout(with: context) } func selectNextSidebarItemWithUnreadArticles() { guard let sidebarItem = nextSidebarItemWithUnreadArticles else { return } coordinator?.selectFeed(sidebarItem, animations: [.navigation, .scroll]) } } // MARK: - Thumbnails private extension MainTimelineViewController { /// Reloads the visible cells for those articles. func thumbnailURLsDidChange(for articleIDs: Set) { guard !articleIDs.isEmpty else { return } reloadCells(visibleArticles().filter { articleIDs.contains($0.articleID) }) } func visibleArticles() -> [Article] { guard let collectionView, let dataSource else { return [] } return collectionView.indexPathsForVisibleItems.compactMap { dataSource.itemIdentifier(for: $0) } } } // MARK: - Notifications API private extension MainTimelineViewController { @objc dynamic func unreadCountDidChange(_ notification: Notification) { Self.logger.debug("MainTimelineViewController: unreadCountDidChange") queueUpdateUI() } @objc func statusesDidChange(_ note: Notification) { Self.logger.debug("MainTimelineViewController: statusesDidChange") guard isViewLoaded, let collectionView, let dataSource else { return } guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set, !articleIDs.isEmpty else { return } let indexPaths = collectionView.indexPathsForVisibleItems if indexPaths.count == 0 { return } var visibleUpdatedArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) }.filter { articleIDs.contains($0.articleID) } // The swiped row is updated in place, since a snapshot reload during the swipe animation triggers a UICollectionView // “unexpected removal of the current swipe occurrence’s mask view” error. A status change doesn’t change a row’s height. if let swipedArticleID, articleIDs.contains(swipedArticleID) { self.swipedArticleID = nil if let index = visibleUpdatedArticles.firstIndex(where: { $0.articleID == swipedArticleID }) { let swipedArticle = visibleUpdatedArticles.remove(at: index) if let indexPath = dataSource.indexPath(for: swipedArticle), let cell = collectionView.cellForItem(at: indexPath) as? MainTimelineCell { cell.cellData = configure(article: swipedArticle) } } } reloadCells(visibleUpdatedArticles) } @objc func handleFeedIconImageDidChange(_ notification: Notification) { Self.logger.debug("MainTimelineViewController: handleFeedIconImageDidChange") queueReloadIfVisibleArticleMightShowIcon(in: notification) } @objc func handleAuthorAvatarImageDidChange(_ notification: Notification) { Self.logger.debug("MainTimelineViewController: handleAuthorAvatarImageDidChange") queueReloadIfVisibleArticleMightShowIcon(in: notification) } @objc func handleGrayscaleIconsDidChange(_ notification: Notification) { Self.logger.debug("MainTimelineViewController: handleGrayscaleIconsDidChange") guard showIcons else { return } reloadVisibleCells() } @objc func timelineIconSizeDidChange(_ note: Notification) { Self.logger.debug("MainTimelineViewController: timelineIconSizeDidChange") if iconSize != AppDefaults.timelineIconSize { iconSize = AppDefaults.timelineIconSize reloadVisibleCells() } } @objc func timelineNumberOfLinesDidChange(_ note: Notification) { Self.logger.debug("MainTimelineViewController: timelineNumberOfLinesDidChange") if numberOfTextLines != AppDefaults.timelineNumberOfLines { numberOfTextLines = AppDefaults.timelineNumberOfLines reloadVisibleCells() } } @objc func handleMarkReadBehaviorDidChange(_ notification: Notification) { markReadBehavior = AppDefaults.markReadBehavior } /// The footer’s height depends on whether it shows an unread count. @objc func handleUnreadCountDisplaySettingDidChange(_ notification: Notification) { updateNextUnreadFooter() invalidateNextUnreadFooterSize() } @objc func handleTimelineThumbnailsDisplayDidChange(_ notification: Notification) { guard thumbnailsDisplay != AppDefaults.timelineThumbnailsDisplay else { return } thumbnailsDisplay = AppDefaults.timelineThumbnailsDisplay if thumbnailMode == nil { ArticleThumbnailFinder.shared.emptyHTMLThumbnailCache() } reloadAllCells() } @objc func handleTimelineFadeReadArticlesDidChange(_ notification: Notification) { guard fadesReadArticles != AppDefaults.timelineFadeReadArticles else { return } fadesReadArticles = AppDefaults.timelineFadeReadArticles reloadVisibleCells() } @objc func handleTimelineFeedNameAndDateAboveTitleDidChange(_ notification: Notification) { guard feedNameAndDateAboveTitle != AppDefaults.timelineFeedNameAndDateAboveTitle else { return } feedNameAndDateAboveTitle = AppDefaults.timelineFeedNameAndDateAboveTitle reloadAllCells() } @objc func handleTimelineShowFullTitlesDidChange(_ notification: Notification) { guard showsFullTitles != AppDefaults.timelineShowFullTitles else { return } showsFullTitles = AppDefaults.timelineShowFullTitles reloadAllCells() } @objc func handleThumbnailDidBecomeAvailable(_ notification: Notification) { guard let thumbnailMode, let collectionView, let dataSource, let url = notification.userInfo?[ThumbnailDownloader.urlKey] as? String else { return } // The row’s height already allows for the thumbnail, so only the cell’s contents change. for indexPath in collectionView.indexPathsForVisibleItems { guard let article = dataSource.itemIdentifier(for: indexPath), ArticleThumbnailFinder.shared.thumbnailURL(for: article, mode: thumbnailMode) == url, let cell = collectionView.cellForItem(at: indexPath) as? MainTimelineCell, let thumbnail = ThumbnailDownloader.shared.thumbnail(url: url, mode: thumbnailMode, feedName: article.feed?.nameForDisplay, articleTitle: article.title) else { continue } cell.thumbnail = thumbnail } } @objc func handleArticleThumbnailDownloadDidFail(_ notification: Notification) { guard thumbnailMode != nil, let articleIDs = notification.userInfo?[ArticleThumbnailFinder.articleIDsKey] as? Set else { return } // Articles that used the failed URL now get their next source, or none. thumbnailURLsDidChange(for: articleIDs) } @objc func handleNetworkStatusDidChange(_ notification: Notification) { guard thumbnailMode != nil, ThumbnailDownloader.shared.networkAllowsDownloads else { return } // Thumbnails that couldn’t download while offline try again. reloadVisibleCells() } @objc func contentSizeCategoryDidChange(_ note: Notification) { Self.logger.debug("MainTimelineViewController: contentSizeCategoryDidChange") reloadVisibleCells() } @objc func displayNameDidChange(_ note: Notification) { Self.logger.debug("MainTimelineViewController: displayNameDidChange") updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "") } @objc func willEnterForeground(_ note: Notification) { Self.logger.debug("MainTimelineViewController: willEnterForeground") queueUpdateUI() } @objc func handleLowMemory(_ note: Notification) { emptyTextSizerCaches() } @objc func handleAppDidGoToBackground(_ note: Notification) { emptyTextSizerCaches() } func emptyTextSizerCaches() { MultilineUILabelSizer.emptyCache() SingleLineUILabelSizer.emptyCache() } } extension MainTimelineViewController: UISearchControllerDelegate { func willPresentSearchController(_ searchController: UISearchController) { coordinator?.beginSearching() searchController.searchBar.showsScopeBar = true } func willDismissSearchController(_ searchController: UISearchController) { searchController.searchBar.showsScopeBar = false // Async to avoid iOS 26 UINavigationBar crashes during the search-bar dismissal // transition — endSearching() mutates the timeline and the navigation stack. DispatchQueue.main.async { self.coordinator?.endSearching() self.updateToolbar() } } } extension MainTimelineViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { let searchScope = SearchScope(rawValue: searchController.searchBar.selectedScopeButtonIndex)! searchArticles(searchController.searchBar.text!, searchScope) } } extension MainTimelineViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { let searchScope = SearchScope(rawValue: selectedScope)! searchArticles(searchBar.text!, searchScope) } } // MARK: Article Actions extension MainTimelineViewController { func toggleRead(_ article: Article) { assert(coordinator != nil) coordinator?.toggleRead(article) } func toggleArticleReadStatusAction(_ article: Article) -> UIAction? { guard !article.status.read || article.isAvailableToMarkUnread else { return nil } let title = article.status.read ? NSLocalizedString("Mark as Unread", comment: "Command") : NSLocalizedString("Mark as Read", comment: "Command") let image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen let action = UIAction(title: title, image: image) { [weak self] _ in // Post the accessibility announcement immediately so VoiceOver // doesn’t lag behind user actions. let announcement = article.status.read ? NSLocalizedString("Marked as Unread", comment: "Accessibility announcement") : NSLocalizedString("Marked as Read", comment: "Accessibility announcement") UIAccessibility.post(notification: .announcement, argument: announcement) DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.0) { self?.toggleRead(article) } } return action } func toggleStar(_ article: Article) { assert(coordinator != nil) coordinator?.toggleStar(article) } func toggleArticleStarStatusAction(_ article: Article) -> UIAction { let title = article.status.starred ? NSLocalizedString("Mark as Unstarred", comment: "Command") : NSLocalizedString("Mark as Starred", comment: "Command") let image = article.status.starred ? Assets.Images.starOpen : Assets.Images.starClosed let action = UIAction(title: title, image: image) { [weak self] _ in // Post the accessibility announcement immediately so VoiceOver // doesn’t lag behind user actions. let announcement = article.status.starred ? NSLocalizedString("Unstarred", comment: "Accessibility announcement") : NSLocalizedString("Starred", comment: "Starred") UIAccessibility.post(notification: .announcement, argument: announcement) DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.0) { self?.toggleStar(article) } } return action } func markAboveAsRead(_ article: Article) { assert(coordinator != nil) coordinator?.markAboveAsRead(article) } func canMarkAboveAsRead(for article: Article) -> Bool { assert(coordinator != nil) return coordinator?.canMarkAboveAsRead(for: article) ?? false } func markAboveAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? { guard canMarkAboveAsRead(for: article), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else { return nil } let title = NSLocalizedString("Mark Above as Read", comment: "Command") let image = Assets.Images.markAboveAsRead let action = UIAction(title: title, image: image) { [weak self] _ in MarkAsReadAlertController.confirm(self, confirmTitle: title, sourceType: contentView) { [weak self] in self?.markAboveAsRead(article) } } return action } func markBelowAsRead(_ article: Article) { assert(coordinator != nil) coordinator?.markBelowAsRead(article) } func canMarkBelowAsRead(for article: Article) -> Bool { assert(coordinator != nil) return coordinator?.canMarkBelowAsRead(for: article) ?? false } func markBelowAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? { guard canMarkBelowAsRead(for: article), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else { return nil } let title = NSLocalizedString("Mark Below as Read", comment: "Command") let image = Assets.Images.markBelowAsRead let action = UIAction(title: title, image: image) { [weak self] _ in MarkAsReadAlertController.confirm(self, confirmTitle: title, sourceType: contentView) { [weak self] in self?.markBelowAsRead(article) } } return action } func markAboveAsReadAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard canMarkAboveAsRead(for: article), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else { return nil } let title = NSLocalizedString("Mark Above as Read", comment: "Command") 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 self?.markAboveAsRead(article) completion(true) } } return action } func markBelowAsReadAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard canMarkBelowAsRead(for: article), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else { return nil } let title = NSLocalizedString("Mark Below as Read", comment: "Command") 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 self?.markBelowAsRead(article) completion(true) } } return action } func timelineFeedIsEqualTo(_ feed: Feed) -> Bool { assert(coordinator != nil) return coordinator?.timelineFeedIsEqualTo(feed) ?? false } func discloseFeed(_ feed: Feed, animations: Animations = []) { assert(coordinator != nil) coordinator?.discloseFeed(feed, animations: animations) } func discloseFeedAction(_ article: Article) -> UIAction? { guard let feed = article.feed, !timelineFeedIsEqualTo(feed) else { return nil } let title = NSLocalizedString("Go to Feed", comment: "Go to Feed") let action = UIAction(title: title, image: Assets.Images.openInSidebar) { [weak self] _ in self?.discloseFeed(feed, animations: [.scroll, .navigation]) } return action } func discloseFeedAlertAction(_ article: Article, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard let feed = article.feed, !timelineFeedIsEqualTo(feed) else { return nil } let title = NSLocalizedString("Go to Feed", comment: "Go to Feed") let action = UIAlertAction(title: title, style: .default) { [weak self] _ in self?.discloseFeed(feed, animations: [.scroll, .navigation]) completion(true) } return action } func markAllAsRead(_ articles: ArticleArray) { assert(coordinator != nil) coordinator?.markAllAsReadInTimeline(articles) } func markAllInFeedAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? { guard let feed = article.feed else { return nil } guard feed.unreadCount > 0, let collectionView, let contentView = 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 action = UIAction(title: title, image: Assets.Images.markAllAsRead) { [weak self] _ in MarkAsReadAlertController.confirm(self, confirmTitle: title, sourceType: contentView) { [weak self] in let articles = feed.fetchUnreadArticles() self?.markAllAsRead(Array(articles)) } } return action } func markAllInFeedAsReadAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard let feed = article.feed else { return nil } guard feed.unreadCount > 0, let collectionView, let contentView = 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?.markAllAsRead(Array(articles)) completion(true) } } return action } func copyArticleURLAction(_ article: Article) -> UIAction? { guard let url = article.preferredURL else { return nil } let title = NSLocalizedString("Copy Article URL", comment: "Command") let action = UIAction(title: title, image: Assets.Images.copy) { _ in UIPasteboard.general.url = url } return action } func copyExternalURLAction(_ article: Article) -> UIAction? { guard let externalLink = article.externalLink, externalLink != article.preferredLink, let url = URL(string: externalLink) else { return nil } let title = NSLocalizedString("Copy External URL", comment: "Command") let action = UIAction(title: title, image: Assets.Images.copy) { _ in UIPasteboard.general.url = url } return action } func showBrowserForArticle(_ article: Article) { assert(coordinator != nil) coordinator?.showBrowserForArticle(article) } func openInBrowserAction(_ article: Article) -> UIAction? { guard article.preferredURL != nil else { return nil } let title = NSLocalizedString("Open in Browser", comment: "Command") let action = UIAction(title: title, image: Assets.Images.safari) { [weak self] _ in self?.showBrowserForArticle(article) } return action } func openInBrowserAlertAction(_ article: Article, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard article.preferredURL != nil else { return nil } let title = NSLocalizedString("Open in Browser", comment: "Command") let action = UIAlertAction(title: title, style: .default) { [weak self] _ in self?.showBrowserForArticle(article) completion(true) } return action } func shareDialogForTableCell(indexPath: IndexPath, url: URL, title: String?) { let activityViewController = UIActivityViewController(url: url, title: title, applicationActivities: nil) guard let collectionView, let cell = collectionView.cellForItem(at: indexPath) else { return } let popoverController = activityViewController.popoverPresentationController popoverController?.sourceView = cell popoverController?.sourceRect = CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height) present(activityViewController, animated: true) } func shareAction(_ article: Article, indexPath: IndexPath) -> UIAction? { guard let url = article.preferredURL else { return nil } let title = NSLocalizedString("Share", comment: "Share button") let action = UIAction(title: title, image: Assets.Images.share) { [weak self] _ in self?.shareDialogForTableCell(indexPath: indexPath, url: url, title: article.title) } return action } func shareAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { guard let url = article.preferredURL else { return nil } let title = NSLocalizedString("Share", comment: "Share button") let action = UIAlertAction(title: title, style: .default) { [weak self] _ in completion(true) self?.shareDialogForTableCell(indexPath: indexPath, url: url, title: article.title) } return action } }