Files
NetNewsWire/iOS/MainTimeline/MainTimelineViewController.swift
T

1479 lines
51 KiB
Swift
Raw Normal View History

2026-01-24 10:50:13 +08:00
//
// MainTimelineViewController.swift
2026-01-24 10:50:13 +08:00
// NetNewsWire-iOS
//
2026-01-25 13:56:56 +08:00
// Created by Stuart Breckenridge on 25/01/2026.
2026-01-24 10:50:13 +08:00
// Copyright © 2026 Ranchero Software. All rights reserved.
//
import UIKit
import os
import WebKit
import RSCore
import RSWeb
2026-05-27 17:15:57 -07:00
import HTMLMetadata
2026-01-24 10:50:13 +08:00
import Account
import Articles
2026-05-29 10:46:00 -07:00
import Images
2026-01-24 10:50:13 +08:00
final class MainTimelineViewController: UIViewController, UndoableCommandRunner {
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
// MARK: Private Variables
private var numberOfTextLines = 0
private var iconSize = IconSize.medium
private lazy var feedTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:)))
private lazy var filterButton = UIBarButtonItem(image: Assets.Images.filter, style: .plain, target: self, action: #selector(toggleFilter(_:)))
private lazy var 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
2026-01-26 22:05:40 -08:00
private var dataSource: UICollectionViewDiffableDataSource<Int, Article>?
var didPushArticleViewController = false
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
private var timelineFeed: SidebarItem? {
assert(coordinator != nil)
return coordinator?.timelineFeed
}
private var showIcons: Bool {
assert(coordinator != nil)
return coordinator?.showIcons ?? false
}
private var currentArticle: Article? {
assert(coordinator != nil)
return coordinator?.currentArticle
}
private var timelineMiddleIndexPath: IndexPath? {
get {
coordinator?.timelineMiddleIndexPath
}
set {
coordinator?.timelineMiddleIndexPath = newValue
}
}
private var isTimelineViewControllerPending: Bool {
get {
coordinator?.isTimelineViewControllerPending ?? false
}
set {
coordinator?.isTimelineViewControllerPending = newValue
}
}
private var timelineIconImage: IconImage? {
assert(coordinator != nil)
return coordinator?.timelineIconImage
}
private var timelineDefaultReadFilterType: ReadFilterType {
return timelineFeed?.defaultReadFilterType ?? .none
}
private var isReadArticlesFiltered: Bool {
assert(coordinator != nil)
return coordinator?.isReadArticlesFiltered ?? false
}
private var isTimelineUnreadAvailable: Bool {
assert(coordinator != nil)
return coordinator?.isTimelineUnreadAvailable ?? false
}
private var isRootSplitCollapsed: Bool {
assert(coordinator != nil)
return coordinator?.isRootSplitCollapsed ?? false
}
private 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
}
2026-01-24 10:50:13 +08:00
private var articles: ArticleArray? {
assert(coordinator != nil)
return coordinator?.articles
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
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 = " " // Placeholder avoids iOS 26 UINavigationBar crash.
label.sizeToFit()
2026-01-24 10:50:13 +08:00
return label
}()
private lazy var navigationBarSubtitleTitleLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 12)
2026-01-24 10:50:13 +08:00
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 = " " // Placeholder avoids iOS 26 UINavigationBar crash.
label.sizeToFit()
2026-01-24 10:50:13 +08:00
return label
}()
// MARK: Variables
weak var coordinator: SceneCoordinator?
var undoableCommands = [UndoableCommand]()
override var keyCommands: [UIKeyCommand]? {
// If the first responder is the WKWebView (PreloadedWebView) we don’t want to supply any keyboard
2026-01-24 10:50:13 +08:00
// commands that the system is looking for by going up the responder chain. They will interfere with
// the WKWebViews built in hardware keyboard shortcuts, specifically the up and down arrow keys.
guard let current = UIResponder.currentFirstResponder, !(current is PreloadedWebView) else { return nil }
return keyboardManager.keyCommands
}
override var canBecomeFirstResponder: Bool {
true
}
2026-01-26 10:57:29 -08:00
// 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
}
2026-01-24 10:50:13 +08:00
// 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")
2026-01-26 10:57:29 -08:00
2026-01-25 13:56:56 +08:00
// MARK: Constants
private let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0)
private let updateQueue = CoalescingQueue(name: "Timeline Update Queue", interval: 0.5, maxInterval: 1.0)
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
// MARK: - IBOutlets
@IBOutlet var markAllAsReadButton: UIBarButtonItem?
2026-01-26 22:05:40 -08:00
@IBOutlet var collectionView: UICollectionView?
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
override func viewDidLoad() {
super.viewDidLoad()
2026-01-26 10:57:29 -08:00
2026-01-26 22:05:40 -08:00
assert(collectionView != nil)
dataSource = makeDataSource(collectionView!)
2026-01-24 10:50:13 +08:00
addNotificationObservers()
2026-01-26 22:05:40 -08:00
assert(dataSource != nil)
configureCollectionView(dataSource!)
2026-01-24 10:50:13 +08:00
configureSearchController()
definesPresentationContext = true
2026-01-24 15:21:34 +08:00
numberOfTextLines = AppDefaults.shared.timelineNumberOfLines
iconSize = AppDefaults.shared.timelineIconSize
2026-01-26 22:05:40 -08:00
assert(collectionView?.refreshControl != nil)
collectionView?.refreshControl = UIRefreshControl()
collectionView?.refreshControl?.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged)
2026-01-24 15:21:34 +08:00
configureToolbar()
resetUI(resetScroll: true)
// Load the table and then scroll to the saved position if available
applyChanges(animated: false) {
if let restoreIndexPath = self.timelineMiddleIndexPath {
2026-01-26 22:05:40 -08:00
self.collectionView?.scrollToItem(at: restoreIndexPath, at: .centeredVertically, animated: false)
2026-01-24 15:21:34 +08:00
}
}
// 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
2026-03-29 21:31:02 -07:00
if #available(iOS 26, *) {
navigationItem.subtitleView = navigationBarSubtitleTitleLabel
}
2026-01-25 13:56:56 +08:00
// Do any additional setup after loading the view.
2026-01-24 10:50:13 +08:00
}
2026-01-26 10:57:29 -08:00
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateToolbarProgressView()
2026-08-25 11:26:21 -07:00
coordinator?.timelineDidLayout()
}
2026-01-24 15:21:34 +08:00
override func viewWillAppear(_ animated: Bool) {
Self.logger.debug("MainTimelineViewController: viewWillAppear")
2026-01-24 15:21:34 +08:00
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.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5141>
navigationItem.largeTitleDisplayMode = .never
2026-01-24 15:21:34 +08:00
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)
2026-01-24 15:21:34 +08:00
}
override func viewDidAppear(_ animated: Bool) {
Self.logger.debug("MainTimelineViewController: viewDidAppear")
2026-01-24 15:21:34 +08:00
super.viewDidAppear(animated)
2026-01-24 15:21:34 +08:00
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.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/5417>
if let coordinator, coordinator.isRootSplitCollapsed,
didPushArticleViewController,
!coordinator.isArticleViewControllerPending {
didPushArticleViewController = false
2026-02-02 22:00:47 +08:00
self.deselectIfNecessary()
}
2026-01-30 06:41:01 +08:00
}
2026-01-30 06:41:01 +08:00
func deselectIfNecessary() {
Self.logger.debug("MainTimelineViewController: deselectIfNecessary")
2026-01-30 13:43:14 -08:00
guard traitCollection.userInterfaceIdiom == .phone else {
return
}
guard let coordinator, coordinator.isRootSplitCollapsed else {
return
}
2026-01-30 13:43:14 -08:00
if coordinator.currentArticle != nil {
Self.logger.debug("MainTimelineViewController: deselectIfNecessary deselecting")
2026-01-30 13:43:14 -08:00
if let indexPath = collectionView?.indexPathsForSelectedItems?.first {
collectionView?.deselectItem(at: indexPath, animated: true)
2026-01-30 06:41:01 +08:00
}
coordinator.selectArticle(nil)
2026-01-24 15:21:34 +08:00
}
}
2026-01-31 21:04:11 -08:00
2026-01-24 10:50:13 +08:00
func restoreSelectionIfNecessary(adjustScroll: Bool) {
Self.logger.debug("MainTimelineViewController: restoreSelectionIfNecessary")
2026-01-26 22:05:40 -08:00
guard let collectionView else {
return
}
if let article = currentArticle, let dataSource, let indexPath = dataSource.indexPath(for: article) {
2026-01-24 10:50:13 +08:00
if adjustScroll {
Self.logger.debug("MainTimelineViewController: restoreSelectionIfNecessary selecting item and adjusting scroll")
2026-01-24 10:50:13 +08:00
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: [])
2026-01-25 13:56:56 +08:00
}
2026-01-24 10:50:13 +08:00
}
}
}
func updateNavigationBarTitle(_ text: String) {
navigationItem.title = text
if let label = navigationItem.titleView as? UILabel {
label.text = text
label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil)
label.sizeToFit()
}
}
func updateNavigationBarSubtitle(_ text: String) {
2026-03-29 21:31:02 -07:00
if #available(iOS 26, *), let label = navigationItem.subtitleView as? UILabel {
2026-01-24 10:50:13 +08:00
label.text = text
label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil)
label.sizeToFit()
}
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
func reinitializeArticles(resetScroll: Bool) {
Self.logger.debug("MainTimelineViewController: reinitializeArticles")
guard isViewLoaded else {
return
}
2026-01-24 10:50:13 +08:00
resetUI(resetScroll: resetScroll)
restoreSelectionIfNecessary(adjustScroll: false)
2026-01-24 10:50:13 +08:00
}
func reloadArticles(animated: Bool) {
Self.logger.debug("MainTimelineViewController: reloadArticles")
guard isViewLoaded else {
return
}
2026-01-24 10:50:13 +08:00
applyChanges(animated: animated)
}
func updateArticleSelection(animations: Animations) {
Self.logger.debug("MainTimelineViewController: updateArticleSelection")
2026-01-26 22:05:40 -08:00
guard isViewLoaded, let collectionView, let dataSource else {
return
}
2026-01-26 10:57:29 -08:00
2026-01-25 13:56:56 +08:00
if let article = currentArticle,
let indexPath = dataSource.indexPath(for: article), let indexPaths = collectionView.indexPathsForSelectedItems {
if indexPaths.contains(indexPath) {
return
}
2026-01-24 23:07:06 +08:00
collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: animations)
2026-01-24 10:50:13 +08:00
} else {
collectionView.selectItem(at: nil, animated: animations.contains(.select), scrollPosition: .centeredVertically)
}
queueUpdateUI()
2026-01-24 10:50:13 +08:00
}
func queueUpdateUI() {
updateQueue.add(self, #selector(updateUI))
}
@objc func updateUI() {
Self.logger.debug("MainTimelineViewController: updateUI")
2026-01-24 10:50:13 +08:00
updateToolbar()
}
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?()
}
2026-01-24 10:50:13 +08:00
}
func showSearchAll() {
navigationItem.searchController?.isActive = true
navigationItem.searchController?.searchBar.selectedScopeButtonIndex = 1
navigationItem.searchController?.searchBar.becomeFirstResponder()
}
func focus() {
Self.logger.debug("MainTimelineViewController: focus")
2026-01-24 10:50:13 +08:00
becomeFirstResponder()
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
// MARK: - Reloading
func queueReloadAvailableCells() {
updateQueue.add(self, #selector(reloadVisibleCells))
2026-01-24 10:50:13 +08:00
}
2026-01-24 15:21:34 +08:00
@objc private func reloadVisibleCells() {
Self.logger.debug("MainTimelineViewController: reloadVisibleCells")
guard isViewLoaded, let collectionView, let dataSource else {
2026-01-24 10:50:13 +08:00
return
}
let indexPaths = collectionView.indexPathsForVisibleItems
let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) }
2026-01-24 15:21:34 +08:00
reloadCells(visibleArticles)
2026-01-24 10:50:13 +08:00
}
2026-01-24 15:21:34 +08:00
private func reloadCells(_ articles: [Article]) {
Self.logger.debug("MainTimelineViewController: reloadCells")
2026-01-26 22:05:40 -08:00
guard !articles.isEmpty, let dataSource else {
2026-01-24 10:50:13 +08:00
return
}
var snapshot = dataSource.snapshot()
2026-01-24 15:21:34 +08:00
snapshot.reloadItems(articles)
2026-01-25 13:56:56 +08:00
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.0, execute: {
2026-01-26 22:05:40 -08:00
guard let dataSource = self.dataSource else {
return
}
2026-06-10 21:25:09 +08:00
dataSource.apply(snapshot, animatingDifferences: false) { [weak self = self] in
2026-01-25 13:56:56 +08:00
self?.restoreSelectionIfNecessary(adjustScroll: false)
}
})
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
@objc func refreshAccounts(_ sender: Any) {
2026-01-26 22:05:40 -08:00
collectionView?.refreshControl?.endRefreshing()
2026-01-24 10:50:13 +08:00
// This is a hack to make sure that an error dialog doesn’t interfere with dismissing the refreshControl.
2026-01-24 10:50:13 +08:00
// 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))
}
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
// 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()
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
// 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")
2026-01-24 10:50:13 +08:00
let articlesToMark = coordinator.articles
2026-01-24 10:50:13 +08:00
if let source = sender as? UIBarButtonItem {
MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: source) { [weak self] in
self?.coordinator?.markAsReadAndShowSidebar(articlesToMark)
2026-01-24 10:50:13 +08:00
}
}
if sender is UIKeyCommand {
2026-01-26 22:05:40 -08:00
guard let collectionView else {
return
}
2026-01-24 10:50:13 +08:00
guard let indexPath = collectionView.indexPathsForSelectedItems?.first, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else {
return
}
MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in
self?.coordinator?.markAsReadAndShowSidebar(articlesToMark)
2026-01-24 10:50:13 +08:00
}
}
}
@IBAction func nextUnread(_ sender: Any) {
2026-01-24 10:50:13 +08:00
assert(coordinator != nil)
coordinator?.selectNextUnread()
2026-01-24 10:50:13 +08:00
}
/*
// 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?) {
2026-01-25 13:56:56 +08:00
// Get the new view controller using segue.destination.
2026-01-24 10:50:13 +08:00
// Pass the selected object to the new view controller.
}
*/
2026-01-25 13:56:56 +08:00
}
2026-01-24 10:50:13 +08:00
2026-01-25 13:56:56 +08:00
// MARK: - UICollectionViewDelegate
extension MainTimelineViewController: UICollectionViewDelegate {
2026-01-25 13:56:56 +08:00
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
2026-01-24 15:21:34 +08:00
becomeFirstResponder()
2026-01-26 22:05:40 -08:00
if let dataSource {
let article = dataSource.itemIdentifier(for: indexPath)
coordinator?.selectArticle(article, animations: [.scroll, .select, .navigation])
}
2026-01-24 15:21:34 +08:00
}
2026-01-26 10:57:29 -08:00
2026-01-25 13:56:56 +08:00
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemsAt indexPaths: [IndexPath], point: CGPoint) -> UIContextMenuConfiguration? {
2026-01-26 22:05:40 -08:00
guard let firstIndex = indexPaths.first, let dataSource, let article = dataSource.itemIdentifier(for: firstIndex) else { return nil }
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
return UIContextMenuConfiguration(identifier: firstIndex.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] _ in
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
guard let self = self else { return nil }
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
var menuElements = [UIMenuElement]()
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
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))
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
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))
}
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
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))
}
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
if let action = self.openInBrowserAction(article) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [action]))
}
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
if let action = self.shareAction(article, indexPath: firstIndex) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [action]))
}
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
return UIMenu(title: "", children: menuElements)
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
})
}
2026-01-26 10:57:29 -08:00
2026-01-25 13:56:56 +08:00
func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, highlightPreviewForItemAt indexPath: IndexPath) -> UITargetedPreview? {
2026-01-24 23:07:06 +08:00
guard let row = configuration.identifier as? Int,
let cell = collectionView.cellForItem(at: IndexPath(row: row, section: 0)),
cell.window != nil else {
2026-01-25 17:29:26 +08:00
return nil
2026-01-24 23:07:06 +08:00
}
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
let previewView = cell.contentView
var bounds = previewView.bounds
2026-01-24 23:07:06 +08:00
let parameters = UIPreviewParameters()
2026-02-02 23:26:10 +08:00
parameters.backgroundColor = cell.isSelected ? cell.backgroundConfiguration?.backgroundColor : .tertiarySystemBackground
if let insets = cell.backgroundConfiguration?.backgroundInsets {
bounds = bounds.inset(by: UIEdgeInsets(top: insets.top,
2026-02-02 23:26:10 +08:00
left: -insets.leading - 4,
bottom: insets.bottom,
2026-02-02 23:26:10 +08:00
right: -insets.trailing - 4))
}
parameters.visiblePath = UIBezierPath(roundedRect: bounds,
2026-01-24 23:07:06 +08:00
cornerRadius: 20)
return UITargetedPreview(view: cell, parameters: parameters)
}
2026-01-26 10:57:29 -08:00
2026-01-25 13:56:56 +08:00
func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, dismissalPreviewForItemAt indexPath: IndexPath) -> UITargetedPreview? {
2026-01-24 23:07:06 +08:00
guard let row = configuration.identifier as? Int,
let cell = collectionView.cellForItem(at: IndexPath(row: row, section: 0)),
cell.window != nil else {
2026-01-25 17:29:26 +08:00
return nil
2026-01-24 23:07:06 +08:00
}
2026-01-26 10:57:29 -08:00
2026-01-24 23:07:06 +08:00
let previewView = cell.contentView
var bounds = previewView.bounds
2026-01-24 23:07:06 +08:00
let parameters = UIPreviewParameters()
2026-02-02 23:26:10 +08:00
parameters.backgroundColor = cell.isSelected ? cell.backgroundConfiguration?.backgroundColor : .tertiarySystemBackground
if let insets = cell.backgroundConfiguration?.backgroundInsets {
bounds = bounds.inset(by: UIEdgeInsets(top: insets.top,
2026-02-02 23:26:10 +08:00
left: -insets.leading - 4,
bottom: insets.bottom,
2026-02-02 23:26:10 +08:00
right: -insets.trailing - 4))
}
parameters.visiblePath = UIBezierPath(roundedRect: bounds,
2026-01-24 23:07:06 +08:00
cornerRadius: 20)
return UITargetedPreview(view: cell, parameters: parameters)
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
}
// 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()
}
}
2026-01-24 10:50:13 +08:00
// MARK: Private API
private extension MainTimelineViewController {
2026-01-26 10:57:29 -08:00
func updateVisibleCellConfigurations() {
guard isViewLoaded, let collectionView else {
return
}
for cell in collectionView.visibleCells {
cell.setNeedsUpdateConfiguration()
}
}
2026-01-24 10:50:13 +08:00
func addNotificationObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(avatarDidBecomeAvailable(_:)), name: .AvatarDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .FaviconDidBecomeAvailable, object: nil)
// TODO: fix this temporary hack, which will probably require refactoring image handling.
// We want to know when to possibly reconfigure our cells with a new image, and we don’t
// always know when an image is available — but watching the .htmlMetadataAvailable Notification
// lets us know that it’s time to request an image.
NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .htmlMetadataAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(timelineIconSizeDidChange(_:)), name: .timelineIconSizeDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(timelineNumberOfLinesDidChange(_:)), name: .timelineNumberOfLinesDidChange, object: nil)
2026-01-24 10:50:13 +08:00
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)
2026-06-22 11:05:02 -07:00
NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
2026-01-24 10:50:13 +08:00
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
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
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
if traitCollection.userInterfaceIdiom == .pad {
searchController.searchBar.selectedScopeButtonIndex = 1
2026-03-29 21:31:02 -07:00
if #available(iOS 26, *) {
navigationItem.searchBarPlacementAllowsExternalIntegration = true
}
2026-01-24 10:50:13 +08:00
}
}
2026-01-26 10:57:29 -08:00
2026-01-26 22:05:40 -08:00
private func configureCollectionView(_ dataSource: UICollectionViewDiffableDataSource<Int, Article>) {
2026-01-24 10:50:13 +08:00
var config = UICollectionLayoutListConfiguration(appearance: .plain)
2026-01-24 15:21:34 +08:00
config.showsSeparators = false
2026-01-24 10:50:13 +08:00
config.headerMode = .none
2026-05-26 16:28:46 -07:00
config.trailingSwipeActionsConfigurationProvider = { [weak self] indexPath in
guard let self else {
return nil
}
2026-01-24 10:50:13 +08:00
guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil }
var actions = [UIContextualAction]()
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
// 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") :
2026-06-09 11:25:32 -07:00
NSLocalizedString("Starred", comment: "Starred")
UIAccessibility.post(notification: .announcement, argument: announcement)
2026-01-25 13:56:56 +08:00
/// The call to `toggleStar` is delayed in order to allow
/// the swipe animation to complete. Calling `toggleStar` with no
/// delay results UICollectionView internal inconsistency: unexpected
/// removal of the current swipe occurrence’s mask view error.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.85) {
2026-01-25 13:56:56 +08:00
self?.toggleStar(article)
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
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")
2026-01-24 10:50:13 +08:00
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel) { _ in
completion(true)
})
self.present(alert, animated: true)
}
}
moreAction.image = Assets.Images.more
moreAction.backgroundColor = UIColor.systemGray
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
actions.append(starAction)
actions.append(moreAction)
let config = UISwipeActionsConfiguration(actions: actions)
2026-01-28 06:49:30 +08:00
config.performsFirstActionWithFullSwipe = true
2026-01-24 10:50:13 +08:00
return config
}
2026-05-26 16:28:46 -07:00
config.leadingSwipeActionsConfigurationProvider = { [weak self] indexPath in
guard let self else {
return nil
}
2026-01-24 10:50:13 +08:00
guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil }
guard !article.status.read || article.isAvailableToMarkUnread else { return nil }
2026-01-24 15:21:34 +08:00
var actions = [UIContextualAction]()
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
// Set up the read action
let readTitle = article.status.read ?
NSLocalizedString("Mark as Unread", comment: "Command") :
NSLocalizedString("Mark as Read", comment: "Command")
2026-01-24 10:50:13 +08:00
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)
2026-01-25 13:56:56 +08:00
/// The call to `toggleRead` is delayed in order to allow
/// the swipe animation to complete. Calling `toggleRead` with no
/// delay results UICollectionView internal inconsistency: unexpected
/// removal of the current swipe occurrence’s mask view error.
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.85) {
2026-01-25 13:56:56 +08:00
self?.toggleRead(article)
}
2026-01-24 10:50:13 +08:00
completion(true)
}
readAction.image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen
readAction.backgroundColor = Assets.Colors.primaryAccent
actions.append(readAction)
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
let config = UISwipeActionsConfiguration(actions: actions)
2026-01-25 13:56:56 +08:00
config.performsFirstActionWithFullSwipe = true
2026-01-24 10:50:13 +08:00
return config
}
2026-01-26 10:57:29 -08:00
2026-01-26 22:05:40 -08:00
collectionView?.refreshControl = UIRefreshControl()
collectionView?.refreshControl?.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged)
collectionView?.contentInsetAdjustmentBehavior = .automatic
2026-01-26 10:57:29 -08:00
let layout = UICollectionViewCompositionalLayout { _, layoutEnvironment in
2026-01-26 23:19:37 +08:00
let listConfig = config
2026-01-26 10:57:29 -08:00
2026-01-26 23:19:37 +08:00
let section = NSCollectionLayoutSection.list(using: listConfig, layoutEnvironment: layoutEnvironment)
2026-01-26 10:57:29 -08:00
2026-01-26 23:19:37 +08:00
/// 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
2026-01-26 23:19:37 +08:00
section.contentInsets = NSDirectionalEdgeInsets(
top: 0,
leading: remainingWidth > 0 ? sidebarOverlapWidth : 0,
2026-01-26 23:19:37 +08:00
bottom: 0,
trailing: 0
)
2026-01-26 10:57:29 -08:00
2026-01-26 23:19:37 +08:00
return section
}
2026-01-24 23:07:06 +08:00
layout.configuration.contentInsetsReference = .safeArea
2026-01-26 22:05:40 -08:00
collectionView?.collectionViewLayout = layout
2026-01-24 10:50:13 +08:00
}
2026-01-26 10:57:29 -08:00
2026-01-26 22:05:40 -08:00
private func makeDataSource(_ collectionView: UICollectionView) -> UICollectionViewDiffableDataSource<Int, Article> {
2026-06-22 10:55:38 -07:00
collectionView.register(MainTimelineCell.self, forCellWithReuseIdentifier: MainTimelineCell.reuseIdentifier)
2026-01-24 10:50:13 +08:00
let dataSource: UICollectionViewDiffableDataSource<Int, Article> =
MainTimelineCollectionViewDataSource(collectionView: collectionView, cellProvider: { [weak self] collectionView, indexPath, article in
guard let self else {
return nil
}
2026-06-22 10:55:38 -07:00
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MainTimelineCell.reuseIdentifier, for: indexPath) as! MainTimelineCell
cell.cellData = self.configure(article: article)
return cell
2026-01-24 10:50:13 +08:00
})
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
return dataSource
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
@discardableResult
private func configure(article: Article) -> MainTimelineCellData {
let iconImage = iconImageFor(article)
let showFeedNames = coordinator?.showFeedNames ?? ShowFeedName.none
let showIcon = showIcons && iconImage != nil
let cellData = MainTimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: iconImage, showIcon: showIcon, numberOfLines: numberOfTextLines, iconSize: iconSize)
return cellData
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
private func iconImageFor(_ article: Article) -> IconImage? {
if !showIcons {
return nil
}
return article.iconImage()
}
2026-01-26 10:57:29 -08:00
2026-01-24 10:50:13 +08:00
func searchArticles(_ searchString: String, _ searchScope: SearchScope) {
assert(coordinator != nil)
coordinator?.searchArticles(searchString, searchScope)
}
func configureToolbar() {
if traitCollection.userInterfaceIdiom == .phone {
2026-03-29 21:31:02 -07:00
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]
}
2026-03-29 21:31:02 -07:00
}
2026-01-24 10:50:13 +08:00
}
updateToolbarProgressView()
2026-01-24 10:50:13 +08:00
}
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
2026-01-24 10:50:13 +08:00
filterButton.accLabelText = NSLocalizedString("Filter Read Articles", comment: "Filter Read Articles")
}
2026-01-26 22:05:40 -08:00
collectionView?.selectItem(at: nil, animated: false, scrollPosition: .top)
2026-01-24 10:50:13 +08:00
if resetScroll {
2026-01-26 22:05:40 -08:00
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)
}
2026-01-24 10:50:13 +08:00
}
}
updateToolbar()
}
func updateToolbar() {
markAllAsReadButton?.isEnabled = isTimelineUnreadAvailable
nextUnreadButton.isEnabled = coordinator?.isNextUnreadAvailable ?? false
if #unavailable(iOS 26) {
rebuildToolbarItems()
2026-01-24 10:50:13 +08:00
}
}
/// 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)
}
2026-01-24 10:50:13 +08:00
func applyChanges(animated: Bool, completion: (() -> Void)? = nil) {
Self.logger.debug("MainTimelineViewController: applyChanges")
2026-01-26 22:05:40 -08:00
guard let dataSource else {
return
}
2026-01-24 10:50:13 +08:00
var snapshot = NSDiffableDataSourceSnapshot<Int, Article>()
snapshot.appendSections([0])
snapshot.appendItems(articles ?? ArticleArray(), toSection: 0)
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
self?.restoreSelectionIfNecessary(adjustScroll: false)
completion?()
}
}
}
// MARK: - Notifications API
private extension MainTimelineViewController {
2026-01-24 10:50:13 +08:00
@objc dynamic func unreadCountDidChange(_ notification: Notification) {
Self.logger.debug("MainTimelineViewController: unreadCountDidChange")
queueUpdateUI()
2026-01-24 10:50:13 +08:00
}
@objc func statusesDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineViewController: statusesDidChange")
2026-01-24 10:50:13 +08:00
guard isViewLoaded, let collectionView, let dataSource else {
2026-01-24 10:50:13 +08:00
return
}
guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set<String>, !articleIDs.isEmpty else {
return
}
let indexPaths = collectionView.indexPathsForVisibleItems
2026-01-24 15:21:34 +08:00
if indexPaths.count == 0 {
return
}
2026-01-24 10:50:13 +08:00
let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) }
let visibleUpdatedArticles = visibleArticles.filter { articleIDs.contains($0.articleID) }
2026-01-24 15:21:34 +08:00
reloadCells(visibleUpdatedArticles)
2026-01-24 10:50:13 +08:00
}
@objc func feedIconDidBecomeAvailable(_ note: Notification) {
Self.logger.debug("MainTimelineViewController: feedIconDidBecomeAvailable")
2026-01-24 10:50:13 +08:00
guard isViewLoaded else {
2026-01-24 10:50:13 +08:00
return
}
queueReloadAvailableCells()
2026-01-24 10:50:13 +08:00
}
@objc func avatarDidBecomeAvailable(_ note: Notification) {
Self.logger.debug("MainTimelineViewController: avatarDidBecomeAvailable")
2026-01-24 10:50:13 +08:00
guard isViewLoaded else {
2026-01-24 10:50:13 +08:00
return
}
queueReloadAvailableCells()
2026-01-24 10:50:13 +08:00
}
@objc func faviconDidBecomeAvailable(_ note: Notification) {
Self.logger.debug("MainTimelineViewController: faviconDidBecomeAvailable")
2026-01-24 10:50:13 +08:00
guard isViewLoaded else {
2026-01-24 10:50:13 +08:00
return
}
queueReloadAvailableCells()
2026-01-24 10:50:13 +08:00
}
@objc func timelineIconSizeDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineViewController: timelineIconSizeDidChange")
if iconSize != AppDefaults.shared.timelineIconSize {
iconSize = AppDefaults.shared.timelineIconSize
reloadVisibleCells()
}
}
2026-01-24 10:50:13 +08:00
@objc func timelineNumberOfLinesDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineViewController: timelineNumberOfLinesDidChange")
if numberOfTextLines != AppDefaults.shared.timelineNumberOfLines {
numberOfTextLines = AppDefaults.shared.timelineNumberOfLines
reloadVisibleCells()
2026-01-24 10:50:13 +08:00
}
}
@objc func contentSizeCategoryDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineViewController: contentSizeCategoryDidChange")
2026-01-24 15:21:34 +08:00
reloadVisibleCells()
2026-01-24 10:50:13 +08:00
}
@objc func displayNameDidChange(_ note: Notification) {
Self.logger.debug("MainTimelineViewController: displayNameDidChange")
2026-01-24 10:50:13 +08:00
updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "")
}
@objc func willEnterForeground(_ note: Notification) {
Self.logger.debug("MainTimelineViewController: willEnterForeground")
queueUpdateUI()
2026-01-24 10:50:13 +08:00
}
2026-06-22 11:05:02 -07:00
@objc func handleLowMemory(_ note: Notification) {
emptyTextSizerCaches()
}
@objc func handleAppDidGoToBackground(_ note: Notification) {
emptyTextSizerCaches()
}
func emptyTextSizerCaches() {
MultilineUILabelSizer.emptyCache()
SingleLineUILabelSizer.emptyCache()
}
2026-01-24 10:50:13 +08:00
@objc func scrollPositionDidChange() {
Self.logger.debug("MainTimelineViewController: scrollPositionDidChange")
2026-01-26 22:05:40 -08:00
timelineMiddleIndexPath = collectionView?.middleVisibleRow()
2026-01-24 10:50:13 +08:00
}
}
extension MainTimelineViewController: UISearchControllerDelegate {
2026-01-24 10:50:13 +08:00
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()
}
2026-01-24 10:50:13 +08:00
}
}
extension MainTimelineViewController: UISearchResultsUpdating {
2026-01-24 10:50:13 +08:00
func updateSearchResults(for searchController: UISearchController) {
let searchScope = SearchScope(rawValue: searchController.searchBar.selectedScopeButtonIndex)!
searchArticles(searchController.searchBar.text!, searchScope)
}
}
extension MainTimelineViewController: UISearchBarDelegate {
2026-01-24 10:50:13 +08:00
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
let searchScope = SearchScope(rawValue: selectedScope)!
searchArticles(searchBar.text!, searchScope)
}
}
// MARK: Article Actions
extension MainTimelineViewController {
2026-01-24 10:50:13 +08:00
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")
2026-01-24 10:50:13 +08:00
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)
}
2026-01-24 10:50:13 +08:00
}
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")
2026-01-24 10:50:13 +08:00
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") :
2026-06-09 11:25:32 -07:00
NSLocalizedString("Starred", comment: "Starred")
UIAccessibility.post(notification: .announcement, argument: announcement)
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1.0) {
self?.toggleStar(article)
}
2026-01-24 10:50:13 +08:00
}
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? {
2026-01-26 22:05:40 -08:00
guard canMarkAboveAsRead(for: article), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else {
2026-01-24 10:50:13 +08:00
return nil
}
let title = NSLocalizedString("Mark Above as Read", comment: "Command")
2026-01-24 10:50:13 +08:00
let image = Assets.Images.markAboveAsRead
let action = UIAction(title: title, image: image) { [weak self] _ in
MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, 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? {
2026-01-26 22:05:40 -08:00
guard canMarkBelowAsRead(for: article), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else {
2026-01-24 10:50:13 +08:00
return nil
}
let title = NSLocalizedString("Mark Below as Read", comment: "Command")
2026-01-24 10:50:13 +08:00
let image = Assets.Images.markBelowAsRead
let action = UIAction(title: title, image: image) { [weak self] _ in
MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in
self?.markBelowAsRead(article)
}
}
return action
}
func markAboveAsReadAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? {
2026-01-26 22:05:40 -08:00
guard canMarkAboveAsRead(for: article), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else {
2026-01-24 10:50:13 +08:00
return nil
}
let title = NSLocalizedString("Mark Above as Read", comment: "Command")
2026-01-24 10:50:13 +08:00
let cancel = {
completion(true)
}
let action = UIAlertAction(title: title, style: .default) { [weak self] _ in
MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, 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? {
2026-01-26 22:05:40 -08:00
guard canMarkBelowAsRead(for: article), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else {
2026-01-24 10:50:13 +08:00
return nil
}
let title = NSLocalizedString("Mark Below as Read", comment: "Command")
2026-01-24 10:50:13 +08:00
let cancel = {
completion(true)
}
let action = UIAlertAction(title: title, style: .default) { [weak self] _ in
MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, 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)
2026-01-24 10:50:13 +08:00
}
func markAllInFeedAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? {
guard let feed = article.feed else {
2026-01-24 10:50:13 +08:00
return nil
}
let fetchedArticles = feed.fetchArticles()
2026-01-24 10:50:13 +08:00
let articles = Array(fetchedArticles)
2026-01-26 22:05:40 -08:00
guard articles.canMarkAllAsRead(), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else {
2026-01-24 10:50:13 +08:00
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, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in
self?.markAllAsRead(articles)
}
}
return action
}
func markAllInFeedAsReadAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? {
guard let feed = article.feed else {
2026-01-24 10:50:13 +08:00
return nil
}
let fetchedArticles = feed.fetchArticles()
2026-01-24 10:50:13 +08:00
let articles = Array(fetchedArticles)
2026-01-26 22:05:40 -08:00
guard articles.canMarkAllAsRead(), let collectionView, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else {
2026-01-24 10:50:13 +08:00
return nil
}
let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command")
2026-01-24 10:50:13 +08:00
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, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in
self?.markAllAsRead(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")
2026-01-24 10:50:13 +08:00
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")
2026-01-24 10:50:13 +08:00
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")
2026-01-24 10:50:13 +08:00
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")
2026-01-24 10:50:13 +08:00
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)
2026-01-26 22:05:40 -08:00
guard let collectionView, let cell = collectionView.cellForItem(at: indexPath) else {
2026-01-24 10:50:13 +08:00
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")
2026-01-24 10:50:13 +08:00
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")
2026-01-24 10:50:13 +08:00
let action = UIAlertAction(title: title, style: .default) { [weak self] _ in
completion(true)
self?.shareDialogForTableCell(indexPath: indexPath, url: url, title: article.title)
}
return action
}
}