From 80c34f907ab02e99847b030528ee2c9c836ab183 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sat, 24 Jan 2026 10:50:13 +0800 Subject: [PATCH 01/15] Init commit with cell and collection code --- .../UIKit/UICollectionView+RSCore.swift | 7 + .../MainTimelineCollectionViewCell.swift | 262 ++++ ...MainTimelineCollectionViewController.swift | 1156 +++++++++++++++++ iOS/MainTimeline/MainTimelineDataSource.swift | 9 + .../MainTimelineViewController.swift | 8 +- 5 files changed, 1438 insertions(+), 4 deletions(-) create mode 100644 iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift create mode 100644 iOS/MainTimeline/MainTimelineCollectionViewController.swift diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift index e3ab8d830..fd71a9829 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift @@ -28,6 +28,13 @@ extension UICollectionView { scrollToItem(at: indexPath, at: .centeredVertically, animated: true) } } + + public func middleVisibleRow() -> IndexPath? { + if indexPathsForVisibleItems.count > 2 { + return indexPathsForVisibleItems[indexPathsForVisibleItems.count / 2] + } + return nil + } } diff --git a/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift new file mode 100644 index 000000000..6e850b43c --- /dev/null +++ b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift @@ -0,0 +1,262 @@ +// +// MainTimelineCollectionViewCell.swift +// NetNewsWire-iOS +// +// Created by Stuart Breckenridge on 24/01/2026. +// Copyright © 2026 Ranchero Software. All rights reserved. +// + +import UIKit + +class MainTimelineCollectionViewCell: UICollectionViewCell { + @IBOutlet var articleContent: UILabel! + @IBOutlet var articleByLine: UILabel! + @IBOutlet var feedIcon: IconView? + @IBOutlet var indicatorView: IconView! + @IBOutlet var articleDate: UILabel! + @IBOutlet var metaDataStackView: UIStackView! + + var cellData: MainTimelineCellData! { + didSet { + configure(cellData) + } + } + + var isPreview: Bool = false + + override func awakeFromNib() { + MainActor.assumeIsolated { + super.awakeFromNib() + indicatorView.alpha = 0.0 + feedIcon?.translatesAutoresizingMaskIntoConstraints = false + configureStackView() + } + } + + override func layoutSubviews() { + super.layoutSubviews() + } + + private func configure(_ cellData: MainTimelineCellData) { + articleContent.numberOfLines = cellData.numberOfLines + addArticleContent(configurationState) + + if cellData.showFeedName == .feed { + articleByLine.text = cellData.feedName + } else if cellData.showFeedName == .byline { + articleByLine.text = cellData.byline + } else if cellData.showFeedName == .none { + articleByLine.text = "" + } + + if feedIcon != nil { + setIconImage(cellData.iconImage, with: cellData.iconSize) + } + + articleDate.text = cellData.dateString + } + + private func updateIndicatorView(_ state: UICellConfigurationState) { + if cellData.read == false { + if indicatorView.alpha == 0.0 { + indicatorView.alpha = 1.0 + } + UIView.animate(withDuration: 0.25) { + self.indicatorView.iconImage = Assets.Images.unreadCellIndicator + self.indicatorView.tintColor = self.isActive(state) ? .white : Assets.Colors.secondaryAccent + } + return + } else if cellData.starred { + if indicatorView.alpha == 0.0 { + indicatorView.alpha = 1.0 + } + UIView.animate(withDuration: 0.25) { + self.indicatorView.iconImage = Assets.Images.starredFeed + self.indicatorView.tintColor = self.isActive(state) ? .white : Assets.Colors.star + } + return + } else if indicatorView.alpha == 1.0 { + UIView.animate(withDuration: 0.25) { + self.indicatorView.alpha = 0.0 + self.indicatorView.iconImage = nil + } + } + } + + private func configureStackView() { + switch traitCollection.preferredContentSizeCategory { + case .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge: + metaDataStackView.axis = .vertical + metaDataStackView.alignment = .leading + metaDataStackView.distribution = .fill + default: + metaDataStackView.axis = .horizontal + metaDataStackView.alignment = .bottom + metaDataStackView.distribution = .fillEqually + } + } + + private func isActive(_ state: UICellConfigurationState) -> Bool { + let active = state.isSwiped || state.isSelected || state.isEditing || state.isHighlighted + if cellData.title.contains("Vouchers") { + print("Vouchers: \(active)") + } + return active + } + + func setIconImage(_ iconImage: IconImage?) { + if feedIcon!.iconImage !== iconImage { + feedIcon!.iconImage = iconImage + } + } + + private func setIconImage(_ iconImage: IconImage?, with size: IconSize) { + feedIcon!.iconImage = iconImage + updateIconViewSizeConstraints(to: size.size) + } + + private func updateIconViewSizeConstraints(to size: CGSize) { + guard feedIcon != nil else { return } + + for constraint in feedIcon!.constraints.compactMap({ $0 }) { + constraint.isActive = false + } + + NSLayoutConstraint.activate([ + feedIcon!.widthAnchor.constraint(equalToConstant: size.width), + feedIcon!.heightAnchor.constraint(equalToConstant: size.height) + ]) + + setNeedsLayout() + } + + private func addArticleContent(_ state: UICellConfigurationState) { + let attributedCellText = NSMutableAttributedString() + + // 1. Prepare Title + if cellData.title != "" { + let titleFont = UIFont.preferredFont(forTextStyle: .headline) + let lineHeight = titleFont.lineHeight + + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.minimumLineHeight = lineHeight + paragraphStyle.maximumLineHeight = lineHeight + paragraphStyle.lineBreakMode = .byWordWrapping + paragraphStyle.lineBreakStrategy = [] + paragraphStyle.hyphenationFactor = 1.0 + paragraphStyle.allowsDefaultTighteningForTruncation = true + + let titleAttributes: [NSAttributedString.Key: Any] = [ + .font: titleFont, + .paragraphStyle: paragraphStyle, + .foregroundColor: titleTextColor(for: state) + ] + + let titleAttributed = NSAttributedString(string: cellData.title, attributes: titleAttributes) + let linesUsed = countLines(of: titleAttributed, width: articleContent.bounds.width) + // 2. Measure Title Height + if linesUsed >= cellData.numberOfLines { + // The title already fills 3 lines, set it and exit + articleContent.attributedText = titleAttributed + articleContent.lineBreakMode = .byTruncatingTail + return + } + + attributedCellText.append(titleAttributed) + } + + // 3. Prepare Summary (Only reached if Title < 3 lines) + if cellData.summary != "" { + let summaryFont = UIFont.preferredFont(forTextStyle: .body) + let summaryLineHeight = summaryFont.lineHeight + + let paragraphStyle = NSMutableParagraphStyle() + paragraphStyle.minimumLineHeight = summaryLineHeight + paragraphStyle.maximumLineHeight = summaryLineHeight + paragraphStyle.lineBreakMode = .byWordWrapping + paragraphStyle.lineBreakStrategy = [] + paragraphStyle.hyphenationFactor = 1.0 + paragraphStyle.allowsDefaultTighteningForTruncation = true + + let summaryAttributes: [NSAttributedString.Key: Any] = [ + .font: summaryFont, + .paragraphStyle: paragraphStyle, + .foregroundColor: titleTextColor(for: state) + ] + + let prefix = cellData.title != "" ? "\n" : "" + let summaryAttributed = NSAttributedString(string: prefix + cellData.summary, attributes: summaryAttributes) + attributedCellText.append(summaryAttributed) + } + + let linesUsed = countLines(of: attributedCellText, width: articleContent.bounds.width) + if linesUsed >= cellData.numberOfLines { + // The title already fills 3 lines, set it and exit + articleContent.attributedText = attributedCellText + articleContent.lineBreakMode = .byTruncatingTail + return + } else { + articleContent.attributedText = attributedCellText + articleContent.lineBreakMode = .byWordWrapping + } + + } + + func titleTextColor(for state: UICellConfigurationState) -> UIColor { + if isActive(state) { + return .white + } else { + return .label + } + } + + func countLines(of attributedString: NSAttributedString, width: CGFloat) -> Int { + let textStorage = NSTextStorage(attributedString: attributedString) + let textContainer = NSTextContainer(size: CGSize(width: width, height: .greatestFiniteMagnitude)) + let layoutManager = NSLayoutManager() + + layoutManager.addTextContainer(textContainer) + textStorage.addLayoutManager(layoutManager) + + textContainer.lineFragmentPadding = 0 // UILabel uses 0 or very small + layoutManager.ensureLayout(for: textContainer) + + var lineCount = 0 + var index = 0 + var lineRange = NSRange() + + while index < layoutManager.numberOfGlyphs { + layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange) + index = NSMaxRange(lineRange) + lineCount += 1 + } + return lineCount + } + + override func updateConfiguration(using state: UICellConfigurationState) { + super.updateConfiguration(using: state) + + var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state) + backgroundConfig.cornerRadius = 20 + if traitCollection.userInterfaceIdiom == .pad { + backgroundConfig.edgesAddingLayoutMarginsToBackgroundInsets = [.leading, .trailing] + backgroundConfig.backgroundInsets = NSDirectionalEdgeInsets(top: 0, leading: !isPreview ? -4 : -12, bottom: 0, trailing: !isPreview ? -4 : -12) + } + + if isActive(state) { + backgroundConfig.backgroundColor = Assets.Colors.primaryAccent + articleContent.textColor = titleTextColor(for: state) + articleDate.textColor = .lightText + articleByLine.textColor = .lightText + } else { + articleContent.textColor = titleTextColor(for: state) + articleDate.textColor = .secondaryLabel + articleByLine.textColor = .secondaryLabel + } + + updateIndicatorView(state) + + self.backgroundConfiguration = backgroundConfig + } + +} diff --git a/iOS/MainTimeline/MainTimelineCollectionViewController.swift b/iOS/MainTimeline/MainTimelineCollectionViewController.swift new file mode 100644 index 000000000..a7579b4eb --- /dev/null +++ b/iOS/MainTimeline/MainTimelineCollectionViewController.swift @@ -0,0 +1,1156 @@ +// +// MainTimelineCollectionViewController.swift +// NetNewsWire-iOS +// +// Created by Stuart Breckenridge on 24/01/2026. +// Copyright © 2026 Ranchero Software. All rights reserved. +// + +import UIKit +import os +import WebKit +import RSCore +import RSWeb +import Account +import Articles + +let standardCellIdentifier = "MainTimelineCellStandard" +let standardCellIdentifierIndex0 = "MainTimelineCellIndexZero" +let standardCellIdentifierIcon = "MainTimelineCellIcon" +let standardCellIdentifierIconIndex0 = "MainTimelineCellIconIndexZero" + + +final class MainTimelineCollectionViewController: UICollectionViewController, UndoableCommandRunner { + + // MARK: Private Variables + private var numberOfTextLines = 0 + private var iconSize = IconSize.medium + private var refreshProgressView: RefreshProgressView? + private lazy var feedTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) + private lazy var filterButton = UIBarButtonItem(image: Assets.Images.filter, style: .plain, target: self, action: #selector(toggleFilter(_:))) + private lazy var firstUnreadButton = UIBarButtonItem(image: Assets.Images.nextUnread, style: .plain, target: self, action: #selector(firstUnread(_:))) + private lazy var dataSource = makeDataSource() + + private var timelineFeed: SidebarItem? { + assert(coordinator != nil) + return coordinator?.timelineFeed + } + + private var showIcons: Bool { + assert(coordinator != nil) + return coordinator?.showIcons ?? false + } + + private var currentArticle: Article? { + assert(coordinator != nil) + return coordinator?.currentArticle + } + + private var timelineMiddleIndexPath: IndexPath? { + get { + coordinator?.timelineMiddleIndexPath + } + set { + coordinator?.timelineMiddleIndexPath = newValue + } + } + + private var isTimelineViewControllerPending: Bool { + get { + coordinator?.isTimelineViewControllerPending ?? false + } + set { + coordinator?.isTimelineViewControllerPending = newValue + } + } + + private var timelineIconImage: IconImage? { + assert(coordinator != nil) + return coordinator?.timelineIconImage + } + + private var timelineDefaultReadFilterType: ReadFilterType { + return timelineFeed?.defaultReadFilterType ?? .none + } + + private var isReadArticlesFiltered: Bool { + assert(coordinator != nil) + return coordinator?.isReadArticlesFiltered ?? false + } + + private var isTimelineUnreadAvailable: Bool { + assert(coordinator != nil) + return coordinator?.isTimelineUnreadAvailable ?? false + } + + private var isRootSplitCollapsed: Bool { + assert(coordinator != nil) + return coordinator?.isRootSplitCollapsed ?? false + } + + private var articles: ArticleArray? { + assert(coordinator != nil) + return coordinator?.articles + } + + private lazy var navigationBarTitleLabel: UILabel = { + let label = UILabel() + label.font = UIFont.preferredFont(forTextStyle: .subheadline).bold() + label.isUserInteractionEnabled = true + label.numberOfLines = 1 + label.textAlignment = .center + label.adjustsFontForContentSizeCategory = false + let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) + label.addGestureRecognizer(tap) + let pointerInteraction = UIPointerInteraction(delegate: nil) + label.addInteraction(pointerInteraction) + return label + }() + + private lazy var navigationBarSubtitleTitleLabel: UILabel = { + let label = UILabel() + label.font = UIFont(name: "Helvetica", size: 12) + label.textColor = .systemGray + label.textAlignment = .center + label.isUserInteractionEnabled = true + label.adjustsFontForContentSizeCategory = false + let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) + label.addGestureRecognizer(tap) + return label + }() + + + // MARK: Variables + weak var coordinator: SceneCoordinator? + var undoableCommands = [UndoableCommand]() + override var keyCommands: [UIKeyCommand]? { + // If the first responder is the WKWebView (PreloadedWebView) we don't want to supply any keyboard + // commands that the system is looking for by going up the responder chain. They will interfere with + // the WKWebViews built in hardware keyboard shortcuts, specifically the up and down arrow keys. + guard let current = UIResponder.currentFirstResponder, !(current is PreloadedWebView) else { return nil } + + return keyboardManager.keyCommands + } + override var canBecomeFirstResponder: Bool { + true + } + + // MARK: Private Constants + private let searchController = UISearchController(searchResultsController: nil) + private let keyboardManager = KeyboardManager(type: .timeline) + private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainTimelineCollectionViewController") + + // MARK: Constantns + let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0) + + + // MARK: - IBOutlets + @IBOutlet var markAllAsReadButton: UIBarButtonItem? + + // MARK: - Lifecycle + + override func viewDidLoad() { + Self.logger.debug("MainTimelineCollectionViewController: viewDidLoad") + assert(coordinator != nil) + + super.viewDidLoad() + + addNotificationObservers() + configureSearchController() + definesPresentationContext = true + + // Uncomment the following line to preserve selection between presentations + self.clearsSelectionOnViewWillAppear = false + + } + + func restoreSelectionIfNecessary(adjustScroll: Bool) { + if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { + if adjustScroll { + collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: []) + } else { + collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically) + } + } + } + + func updateNavigationBarTitle(_ text: String) { + navigationItem.title = text + if let label = navigationItem.titleView as? UILabel { + label.text = text + label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) + label.sizeToFit() + } + } + + func updateNavigationBarSubtitle(_ text: String) { + if let label = navigationItem.subtitleView as? UILabel { + label.text = text + label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) + label.sizeToFit() + } + } + + func reinitializeArticles(resetScroll: Bool) { + Self.logger.debug("MainTimelineViewController: reinitializeArticles") + resetUI(resetScroll: resetScroll) + } + + func reloadArticles(animated: Bool) { + Self.logger.debug("MainTimelineViewController: reloadArticles") + applyChanges(animated: animated) + } + + func updateArticleSelection(animations: Animations) { + Self.logger.debug("MainTimelineViewController: updateArticleSelection") + + if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { + if collectionView.indexPathsForSelectedItems?.first != indexPath { + collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: animations) + } + } else { + collectionView.selectItem(at: nil, animated: animations.contains(.select), scrollPosition: .centeredVertically) + } + + updateUI() + } + + func updateUI() { + Self.logger.debug("MainTimelineViewController: updateUI") + + refreshProgressView?.update() + updateToolbar() + } + + func hideSearch() { + navigationItem.searchController?.isActive = false + } + + func showSearchAll() { + navigationItem.searchController?.isActive = true + navigationItem.searchController?.searchBar.selectedScopeButtonIndex = 1 + navigationItem.searchController?.searchBar.becomeFirstResponder() + } + + func focus() { + Self.logger.debug("MainTimelineViewController: focus") + becomeFirstResponder() + } + + // MARK: - Reloading + + func queueReloadAvailableCells() { + CoalescingQueue.standard.add(self, #selector(reconfigureVisibleCells)) + } + + @objc private func reconfigureVisibleCells() { + guard isViewLoaded, view.window != nil else { + return + } + let indexPaths = collectionView.indexPathsForVisibleItems + + let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } + reconfigureCells(visibleArticles) + } + + private func reconfigureCells(_ articles: [Article]) { + guard !articles.isEmpty else { + return + } + + var snapshot = dataSource.snapshot() + snapshot.reconfigureItems(articles) + dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in + self?.restoreSelectionIfNecessary(adjustScroll: false) + } + } + + @objc func refreshAccounts(_ sender: Any) { + collectionView.refreshControl?.endRefreshing() + + // This is a hack to make sure that an error dialog doesn't interfere with dismissing the refreshControl. + // If the error dialog appears too closely to the call to endRefreshing, then the refreshControl never disappears. + DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { + appDelegate.manualRefresh(errorHandler: ErrorHandler.present(self)) + } + } + + // MARK: - Keyboard shortcuts + + @objc func selectNextUp(_ sender: Any?) { + assert(coordinator != nil) + coordinator?.selectPrevArticle() + } + + @objc func selectNextDown(_ sender: Any?) { + assert(coordinator != nil) + coordinator?.selectNextArticle() + } + + @objc func navigateToSidebar(_ sender: Any?) { + assert(coordinator != nil) + coordinator?.navigateToFeeds() + } + + @objc func navigateToDetail(_ sender: Any?) { + assert(coordinator != nil) + coordinator?.navigateToDetail() + } + + @objc func showFeedInspector(_ sender: Any?) { + assert(coordinator != nil) + coordinator?.showFeedInspector() + } + + // MARK: - IBActions + + @objc func openInBrowser(_ sender: Any?) { + assert(coordinator != nil) + coordinator?.showBrowserForCurrentArticle() + } + + @objc func openInAppBrowser(_ sender: Any?) { + assert(coordinator != nil) + coordinator?.showInAppBrowser() + } + + @IBAction func toggleFilter(_ sender: Any) { + assert(coordinator != nil) + coordinator?.toggleReadArticlesFilter() + } + + private func markAllAsReadInTimeline() { + assert(coordinator != nil) + coordinator?.markAllAsReadInTimeline() + } + + @IBAction func markAllAsRead(_ sender: Any?) { + let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read") + + if let source = sender as? UIBarButtonItem { + MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: source) { [weak self] in + self?.markAllAsReadInTimeline() + } + } + + if sender is UIKeyCommand { + guard let indexPath = collectionView.indexPathsForSelectedItems?.first, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else { + return + } + + MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in + self?.markAllAsReadInTimeline() + } + } + } + + @IBAction func firstUnread(_ sender: Any) { + assert(coordinator != nil) + coordinator?.selectFirstUnread() + } + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. + } + */ + + // MARK: UICollectionViewDataSource + + override func numberOfSections(in collectionView: UICollectionView) -> Int { + // #warning Incomplete implementation, return the number of sections + return 0 + } + + + override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + // #warning Incomplete implementation, return the number of items + return 0 + } + + override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifier, for: indexPath) + + // Configure the cell + + return cell + } + + // MARK: UICollectionViewDelegate + + /* + // Uncomment this method to specify if the specified item should be highlighted during tracking + override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { + return true + } + */ + + /* + // Uncomment this method to specify if the specified item should be selected + override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { + return true + } + */ + + /* + // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item + override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { + return false + } + + override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { + return false + } + + override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { + + } + */ + +} + + +// MARK: Private API +private extension MainTimelineCollectionViewController { + + 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(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } + NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange), name: .DisplayNameDidChange, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) + } + + private func configureSearchController() { + // Setup the Search Controller + searchController.delegate = self + searchController.searchResultsUpdater = self + searchController.obscuresBackgroundDuringPresentation = false + searchController.searchBar.delegate = self + searchController.searchBar.placeholder = NSLocalizedString("Search Articles", comment: "Search Articles") + searchController.searchBar.scopeButtonTitles = [ + NSLocalizedString("Here", comment: "Here"), + NSLocalizedString("All Articles", comment: "All Articles") + ] + searchController.searchBar.barTintColor = .clear + searchController.searchBar.scopeBarBackgroundImage = UIImage() + searchController.searchBar.autocapitalizationType = .none + navigationItem.searchController = searchController + + if traitCollection.userInterfaceIdiom == .pad { + searchController.searchBar.selectedScopeButtonIndex = 1 + navigationItem.searchBarPlacementAllowsExternalIntegration = true + } + } + + private func configureCollectionView() { + var config = UICollectionLayoutListConfiguration(appearance: .plain) + config.separatorConfiguration.color = .separator + config.headerMode = .none + + config.trailingSwipeActionsConfigurationProvider = { [unowned self] indexPath in + guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } + var actions = [UIContextualAction]() + + // Set up the star action + let starTitle = article.status.starred ? + NSLocalizedString("Unstar", comment: "Unstar") : + NSLocalizedString("Star", comment: "Star") + + let starAction = UIContextualAction(style: .normal, title: starTitle) { [weak self] _, _, completion in + 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") + 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 = false + + return config + } + + config.leadingSwipeActionsConfigurationProvider = { [unowned self] indexPath in + guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } + var actions = [UIContextualAction]() + + guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } + guard !article.status.read || article.isAvailableToMarkUnread else { return nil } + + // Set up the read action + let readTitle = article.status.read ? + NSLocalizedString("Mark as Unread", comment: "Mark as Unread") : + NSLocalizedString("Mark as Read", comment: "Mark as Read") + + let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] _, _, completion in + 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 = false + return config + } + + + let layout = UICollectionViewCompositionalLayout.list(using: config) + collectionView.setCollectionViewLayout(layout, animated: false) + collectionView.refreshControl = UIRefreshControl() + collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) + + if config.appearance == .sidebar { + // This defrosts the glass. + collectionView.backgroundColor = .clear + } + } + + private func makeDataSource() -> UICollectionViewDiffableDataSource { + let dataSource: UICollectionViewDiffableDataSource = + MainTimelineCollectionViewDataSource(collectionView: collectionView, cellProvider: { [weak self] collectionView, indexPath, article in + let cellData = self!.configure(article: article) + if self!.showIcons { + if indexPath.row == 0 { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifierIconIndex0, for: indexPath) as! MainTimelineCollectionViewCell + cell.cellData = cellData + return cell + } else { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifierIcon, for: indexPath) as! MainTimelineCollectionViewCell + cell.cellData = cellData + return cell + } + } else { + if indexPath.row == 0 { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifierIndex0, for: indexPath) as! MainTimelineCollectionViewCell + cell.cellData = cellData + return cell + } else { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifier, for: indexPath) as! MainTimelineCollectionViewCell + cell.cellData = cellData + return cell + } + } + + }) + + return dataSource + } + + @discardableResult + private func configure(article: Article) -> MainTimelineCellData { + let iconImage = iconImageFor(article) + let showFeedNames = coordinator?.showFeedNames ?? ShowFeedName.none + let showIcon = showIcons && iconImage != nil + let cellData = MainTimelineCellData(article: article, showFeedName: showFeedNames, feedName: article.feed?.nameForDisplay, byline: article.byline(), iconImage: iconImage, showIcon: showIcon, numberOfLines: numberOfTextLines, iconSize: iconSize) + return cellData + } + + private func iconImageFor(_ article: Article) -> IconImage? { + if !showIcons { + return nil + } + return article.iconImage() + } + + func searchArticles(_ searchString: String, _ searchScope: SearchScope) { + assert(coordinator != nil) + coordinator?.searchArticles(searchString, searchScope) + } + + func configureToolbar() { + if traitCollection.userInterfaceIdiom == .phone { + toolbarItems?.insert(.flexibleSpace(), at: 1) + toolbarItems?.insert(navigationItem.searchBarPlacementBarButtonItem, at: 2) + } + } + + func resetUI(resetScroll: Bool) { + let shouldShowFilterButton = coordinator?.shouldShowFilterButton() ?? false + navigationItem.rightBarButtonItem = shouldShowFilterButton ? filterButton : nil + + if isReadArticlesFiltered { + filterButton.style = .prominent + filterButton.tintColor = Assets.Colors.primaryAccent + filterButton.accLabelText = NSLocalizedString("Selected - Filter Read Articles", comment: "Selected - Filter Read Articles") + } else { + filterButton.style = .plain + filterButton.tintColor = nil + filterButton.accLabelText = NSLocalizedString("Filter Read Articles", comment: "Filter Read Articles") + } + + collectionView.selectItem(at: nil, animated: false, scrollPosition: .top) + + if resetScroll { + let snapshot = dataSource.snapshot() + if snapshot.sectionIdentifiers.count > 0 && snapshot.itemIdentifiers(inSection: 0).count > 0 { + collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: .top) + } + } + + updateToolbar() + } + + func updateToolbar() { + markAllAsReadButton?.isEnabled = isTimelineUnreadAvailable + firstUnreadButton.isEnabled = coordinator?.isAnyUnreadAvailable ?? false + + if isRootSplitCollapsed { + if let toolbarItems = toolbarItems, toolbarItems.last != firstUnreadButton { + var items = toolbarItems + items.append(firstUnreadButton) + setToolbarItems(items, animated: false) + } + } else { + if let toolbarItems = toolbarItems, toolbarItems.last == firstUnreadButton { + let items = Array(toolbarItems[0.. Void)? = nil) { + var snapshot = NSDiffableDataSourceSnapshot() + 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 MainTimelineCollectionViewController { + @objc dynamic func unreadCountDidChange(_ notification: Notification) { + Self.logger.debug("MainTimelineViewController: unreadCountDidChange") + updateUI() + } + + @objc func statusesDidChange(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: statusesDidChange") + + guard isViewLoaded, view.window != nil 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 } + + let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } + let visibleUpdatedArticles = visibleArticles.filter { articleIDs.contains($0.articleID) } + reconfigureCells(visibleUpdatedArticles) + } + + @objc func feedIconDidBecomeAvailable(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: feedIconDidBecomeAvailable") + + guard isViewLoaded, view.window != nil else { + return + } + guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed else { + return + } + + updateIconForVisibleArticles(feed) + } + + @objc func avatarDidBecomeAvailable(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: avatarDidBecomeAvailable") + + guard isViewLoaded, view.window != nil else { + return + } + guard showIcons, let avatarURL = note.userInfo?[UserInfoKey.url] as? String else { + return + } + let indexPaths = collectionView.indexPathsForVisibleItems + + let articlesToReload = indexPaths.compactMap { indexPath -> Article? in + guard let article = dataSource.itemIdentifier(for: indexPath), + let authors = article.authors, + !authors.isEmpty else { + return nil + } + for author in authors { + if author.avatarURL == avatarURL { + return article + } + } + return nil + } + reconfigureCells(articlesToReload) + } + + @objc func faviconDidBecomeAvailable(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: faviconDidBecomeAvailable") + + guard isViewLoaded, view.window != nil else { + return + } + + updateIconForVisibleArticles() + } + + /// Update icon for all visible articles — or, if feed is non-nil, update articles only from that feed. + private func updateIconForVisibleArticles(_ feed: Feed? = nil) { + guard isViewLoaded, view.window != nil else { + return + } + guard showIcons else { + return + } + let indexPaths = collectionView.indexPathsForVisibleItems + + let articlesToReload = indexPaths.compactMap { indexPath -> Article? in + guard let article = dataSource.itemIdentifier(for: indexPath) else { + return nil + } + if feed == nil || feed == article.feed { + return article + } + return nil + } + reconfigureCells(articlesToReload) + } + + func userDefaultsDidChange() { + Self.logger.debug("MainTimelineViewController: userDefaultsDidChange") + + if self.numberOfTextLines != AppDefaults.shared.timelineNumberOfLines || self.iconSize != AppDefaults.shared.timelineIconSize { + self.numberOfTextLines = AppDefaults.shared.timelineNumberOfLines + self.iconSize = AppDefaults.shared.timelineIconSize + self.reconfigureVisibleCells() + } + self.updateToolbar() + } + + @objc func contentSizeCategoryDidChange(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: contentSizeCategoryDidChange") + reconfigureVisibleCells() + } + + @objc func displayNameDidChange(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: displayNameDidChange") + updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "") + } + + @objc func willEnterForeground(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: willEnterForeground") + updateUI() + } + + @objc func scrollPositionDidChange() { + Self.logger.debug("MainTimelineViewController: scrollPositionDidChange") + timelineMiddleIndexPath = collectionView.middleVisibleRow() + } + +} + + +extension MainTimelineCollectionViewController: UISearchControllerDelegate { + + func willPresentSearchController(_ searchController: UISearchController) { + coordinator?.beginSearching() + searchController.searchBar.showsScopeBar = true + } + + func willDismissSearchController(_ searchController: UISearchController) { + coordinator?.endSearching() + searchController.searchBar.showsScopeBar = false + updateToolbar() + } + +} + +extension MainTimelineCollectionViewController: UISearchResultsUpdating { + + func updateSearchResults(for searchController: UISearchController) { + let searchScope = SearchScope(rawValue: searchController.searchBar.selectedScopeButtonIndex)! + searchArticles(searchController.searchBar.text!, searchScope) + } + +} + +extension MainTimelineCollectionViewController: UISearchBarDelegate { + func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { + let searchScope = SearchScope(rawValue: selectedScope)! + searchArticles(searchBar.text!, searchScope) + } +} + +// MARK: Article Actions +extension MainTimelineCollectionViewController { + 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: "Mark as Unread") : + NSLocalizedString("Mark as Read", comment: "Mark as Read") + let image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen + + let action = UIAction(title: title, image: image) { [weak self] _ in + 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: "Mark as Unstarred") : + NSLocalizedString("Mark as Starred", comment: "Mark as Starred") + let image = article.status.starred ? Assets.Images.starOpen : Assets.Images.starClosed + + let action = UIAction(title: title, image: image) { [weak self] _ in + 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 contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { + return nil + } + + let title = NSLocalizedString("Mark Above as Read", comment: "Mark Above as Read") + 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? { + guard canMarkBelowAsRead(for: article), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { + return nil + } + + let title = NSLocalizedString("Mark Below as Read", comment: "Mark Below as Read") + 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? { + guard canMarkAboveAsRead(for: article), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { + return nil + } + + let title = NSLocalizedString("Mark Above as Read", comment: "Mark Above as Read") + 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? { + guard canMarkBelowAsRead(for: article), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { + return nil + } + + let title = NSLocalizedString("Mark Below as Read", comment: "Mark Below as Read") + 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?.markAllAsRead(articles) + } + + func markAllInFeedAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? { + guard let feed = article.feed else { return nil } + guard let fetchedArticles = try? feed.fetchArticles() else { + return nil + } + + let articles = Array(fetchedArticles) + guard articles.canMarkAllAsRead(), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { + return nil + } + + let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") + let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String + + let 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 { return nil } + guard let fetchedArticles = try? feed.fetchArticles() else { + return nil + } + + let articles = Array(fetchedArticles) + guard articles.canMarkAllAsRead(), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { + return nil + } + + let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Mark All as Read in Feed") + 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: "Copy Article URL") + 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: "Copy External URL") + 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: "Open in Browser") + 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: "Open in Browser") + 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 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") + 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") + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in + completion(true) + self?.shareDialogForTableCell(indexPath: indexPath, url: url, title: article.title) + } + return action + } +} diff --git a/iOS/MainTimeline/MainTimelineDataSource.swift b/iOS/MainTimeline/MainTimelineDataSource.swift index 9b3925fbe..8374ad5ee 100644 --- a/iOS/MainTimeline/MainTimelineDataSource.swift +++ b/iOS/MainTimeline/MainTimelineDataSource.swift @@ -14,3 +14,12 @@ final class MainTimelineDataSource: U true } } + + +final class MainTimelineCollectionViewDataSource: UICollectionViewDiffableDataSource where SectionIdentifierType: Hashable, ItemIdentifierType: Hashable { + + override func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { + false + } + +} diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift index 6224036ee..1429ced18 100644 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ b/iOS/MainTimeline/MainTimelineViewController.swift @@ -14,10 +14,10 @@ import RSWeb import Account import Articles -let standardCellIdentifier = "MainTimelineCellStandard" -let standardCellIdentifierIndex0 = "MainTimelineCellIndexZero" -let standardCellIdentifierIcon = "MainTimelineCellIcon" -let standardCellIdentifierIconIndex0 = "MainTimelineCellIconIndexZero" +//let standardCellIdentifier = "MainTimelineCellStandard" +//let standardCellIdentifierIndex0 = "MainTimelineCellIndexZero" +//let standardCellIdentifierIcon = "MainTimelineCellIcon" +//let standardCellIdentifierIconIndex0 = "MainTimelineCellIconIndexZero" final class MainTimelineViewController: UITableViewController, UndoableCommandRunner { From 3836d08b1107d43392068e9f70c00e571082e435 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sat, 24 Jan 2026 15:21:34 +0800 Subject: [PATCH 02/15] Additional collection view work --- iOS/Base.lproj/Main.storyboard | 370 +++++++++++++++++- .../MainTimelineCollectionViewCell.swift | 30 +- ...MainTimelineCollectionViewController.swift | 141 ++++--- iOS/SceneCoordinator.swift | 4 +- 4 files changed, 474 insertions(+), 71 deletions(-) diff --git a/iOS/Base.lproj/Main.storyboard b/iOS/Base.lproj/Main.storyboard index a1e944b44..29398c0ae 100644 --- a/iOS/Base.lproj/Main.storyboard +++ b/iOS/Base.lproj/Main.storyboard @@ -464,16 +464,378 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -795,7 +1157,7 @@ - + @@ -882,7 +1244,7 @@ - + diff --git a/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift index 6e850b43c..579504e61 100644 --- a/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift +++ b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift @@ -63,19 +63,21 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { } UIView.animate(withDuration: 0.25) { self.indicatorView.iconImage = Assets.Images.unreadCellIndicator - self.indicatorView.tintColor = self.isActive(state) ? .white : Assets.Colors.secondaryAccent + self.indicatorView.tintColor = Assets.Colors.secondaryAccent } return - } else if cellData.starred { + } + else if cellData.starred { if indicatorView.alpha == 0.0 { indicatorView.alpha = 1.0 } UIView.animate(withDuration: 0.25) { self.indicatorView.iconImage = Assets.Images.starredFeed - self.indicatorView.tintColor = self.isActive(state) ? .white : Assets.Colors.star + self.indicatorView.tintColor = Assets.Colors.star } return - } else if indicatorView.alpha == 1.0 { + } + else if indicatorView.alpha == 1.0 { UIView.animate(withDuration: 0.25) { self.indicatorView.alpha = 0.0 self.indicatorView.iconImage = nil @@ -98,21 +100,13 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { private func isActive(_ state: UICellConfigurationState) -> Bool { let active = state.isSwiped || state.isSelected || state.isEditing || state.isHighlighted - if cellData.title.contains("Vouchers") { - print("Vouchers: \(active)") - } return active } - func setIconImage(_ iconImage: IconImage?) { - if feedIcon!.iconImage !== iconImage { - feedIcon!.iconImage = iconImage - } - } private func setIconImage(_ iconImage: IconImage?, with size: IconSize) { - feedIcon!.iconImage = iconImage updateIconViewSizeConstraints(to: size.size) + feedIcon!.iconImage = iconImage } private func updateIconViewSizeConstraints(to size: CGSize) { @@ -203,7 +197,7 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { } func titleTextColor(for state: UICellConfigurationState) -> UIColor { - if isActive(state) { + if state.isSelected { return .white } else { return .label @@ -243,7 +237,12 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { backgroundConfig.backgroundInsets = NSDirectionalEdgeInsets(top: 0, leading: !isPreview ? -4 : -12, bottom: 0, trailing: !isPreview ? -4 : -12) } - if isActive(state) { + if state.isSwiped { + backgroundConfig.backgroundColor = .secondarySystemFill + articleContent.textColor = titleTextColor(for: state) + articleDate.textColor = .secondaryLabel + articleByLine.textColor = .secondaryLabel + } else if state.isSelected { backgroundConfig.backgroundColor = Assets.Colors.primaryAccent articleContent.textColor = titleTextColor(for: state) articleDate.textColor = .lightText @@ -260,3 +259,4 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { } } + diff --git a/iOS/MainTimeline/MainTimelineCollectionViewController.swift b/iOS/MainTimeline/MainTimelineCollectionViewController.swift index a7579b4eb..b90ee42c1 100644 --- a/iOS/MainTimeline/MainTimelineCollectionViewController.swift +++ b/iOS/MainTimeline/MainTimelineCollectionViewController.swift @@ -156,13 +156,76 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un super.viewDidLoad() addNotificationObservers() + configureCollectionView() configureSearchController() definesPresentationContext = true // Uncomment the following line to preserve selection between presentations self.clearsSelectionOnViewWillAppear = false + + numberOfTextLines = AppDefaults.shared.timelineNumberOfLines + iconSize = AppDefaults.shared.timelineIconSize + + collectionView.refreshControl = UIRefreshControl() + collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) + + configureToolbar() + resetUI(resetScroll: true) + + // Load the table and then scroll to the saved position if available + applyChanges(animated: false) { + if let restoreIndexPath = self.timelineMiddleIndexPath { + self.collectionView.scrollToItem(at: restoreIndexPath, at: .centeredVertically, animated: false) + } + } + + // Disable swipe back on iPad Mice + guard let gesture = self.navigationController?.interactivePopGestureRecognizer as? UIPanGestureRecognizer else { + return + } + gesture.allowedScrollTypesMask = [] + + navigationItem.title = nil // Don’t let "Timeline" accidentally show + navigationItem.largeTitleDisplayMode = .never + navigationItem.titleView = navigationBarTitleLabel + navigationItem.subtitleView = navigationBarSubtitleTitleLabel } + + 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 + } + + updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "") + coordinator?.updateNavigationBarSubtitles(nil) + } + + override func viewDidAppear(_ animated: Bool) { + Self.logger.debug("MainTimelineViewController: viewDidAppear") + + super.viewDidAppear(true) + isTimelineViewControllerPending = false + if navigationController?.navigationBar.alpha == 0 { + UIView.animate(withDuration: 0.5) { + self.navigationController?.navigationBar.alpha = 1 + } + } + if traitCollection.userInterfaceIdiom == .phone { + if coordinator?.currentArticle != nil { + if let indexPath = collectionView.indexPathsForSelectedItems?.first { + collectionView.deselectItem(at: indexPath, animated: true) + } + coordinator?.selectArticle(nil) + } + } + } func restoreSelectionIfNecessary(adjustScroll: Bool) { if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { @@ -240,26 +303,26 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un // MARK: - Reloading func queueReloadAvailableCells() { - CoalescingQueue.standard.add(self, #selector(reconfigureVisibleCells)) + CoalescingQueue.standard.add(self, #selector(reloadVisibleCells)) } - @objc private func reconfigureVisibleCells() { + @objc private func reloadVisibleCells() { guard isViewLoaded, view.window != nil else { return } let indexPaths = collectionView.indexPathsForVisibleItems let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } - reconfigureCells(visibleArticles) + reloadCells(visibleArticles) } - private func reconfigureCells(_ articles: [Article]) { + private func reloadCells(_ articles: [Article]) { guard !articles.isEmpty else { return } var snapshot = dataSource.snapshot() - snapshot.reconfigureItems(articles) + snapshot.reloadItems(articles) dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in self?.restoreSelectionIfNecessary(adjustScroll: false) } @@ -361,34 +424,17 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un // MARK: UICollectionViewDataSource - override func numberOfSections(in collectionView: UICollectionView) -> Int { - // #warning Incomplete implementation, return the number of sections - return 0 - } - - - override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - // #warning Incomplete implementation, return the number of items - return 0 - } - - override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifier, for: indexPath) - - // Configure the cell - - return cell - } + override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + becomeFirstResponder() + let article = dataSource.itemIdentifier(for: indexPath) + coordinator?.selectArticle(article, animations: [.scroll, .select, .navigation]) + } // MARK: UICollectionViewDelegate - - /* - // Uncomment this method to specify if the specified item should be highlighted during tracking - override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { - return true - } - */ - + + + + /* // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { @@ -464,7 +510,7 @@ private extension MainTimelineCollectionViewController { private func configureCollectionView() { var config = UICollectionLayoutListConfiguration(appearance: .plain) - config.separatorConfiguration.color = .separator + config.showsSeparators = false config.headerMode = .none config.trailingSwipeActionsConfigurationProvider = { [unowned self] indexPath in @@ -542,14 +588,12 @@ private extension MainTimelineCollectionViewController { return config } - config.leadingSwipeActionsConfigurationProvider = { [unowned self] indexPath in - guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - var actions = [UIContextualAction]() - + guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } guard !article.status.read || article.isAvailableToMarkUnread else { return nil } - + var actions = [UIContextualAction]() + // Set up the read action let readTitle = article.status.read ? NSLocalizedString("Mark as Unread", comment: "Mark as Unread") : @@ -569,16 +613,11 @@ private extension MainTimelineCollectionViewController { return config } - let layout = UICollectionViewCompositionalLayout.list(using: config) collectionView.setCollectionViewLayout(layout, animated: false) collectionView.refreshControl = UIRefreshControl() collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) - - if config.appearance == .sidebar { - // This defrosts the glass. - collectionView.backgroundColor = .clear - } + collectionView.allowsMultipleSelection = false } private func makeDataSource() -> UICollectionViewDiffableDataSource { @@ -659,7 +698,7 @@ private extension MainTimelineCollectionViewController { if resetScroll { 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) + //collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: .top) } } @@ -716,11 +755,13 @@ private extension MainTimelineCollectionViewController { return } let indexPaths = collectionView.indexPathsForVisibleItems - if indexPaths.count == 0 { return } + if indexPaths.count == 0 { + return + } let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } let visibleUpdatedArticles = visibleArticles.filter { articleIDs.contains($0.articleID) } - reconfigureCells(visibleUpdatedArticles) + reloadCells(visibleUpdatedArticles) } @objc func feedIconDidBecomeAvailable(_ note: Notification) { @@ -760,7 +801,7 @@ private extension MainTimelineCollectionViewController { } return nil } - reconfigureCells(articlesToReload) + reloadCells(articlesToReload) } @objc func faviconDidBecomeAvailable(_ note: Notification) { @@ -792,7 +833,7 @@ private extension MainTimelineCollectionViewController { } return nil } - reconfigureCells(articlesToReload) + reloadCells(articlesToReload) } func userDefaultsDidChange() { @@ -801,14 +842,14 @@ private extension MainTimelineCollectionViewController { if self.numberOfTextLines != AppDefaults.shared.timelineNumberOfLines || self.iconSize != AppDefaults.shared.timelineIconSize { self.numberOfTextLines = AppDefaults.shared.timelineNumberOfLines self.iconSize = AppDefaults.shared.timelineIconSize - self.reconfigureVisibleCells() + self.reloadVisibleCells() } self.updateToolbar() } @objc func contentSizeCategoryDidChange(_ note: Notification) { Self.logger.debug("MainTimelineViewController: contentSizeCategoryDidChange") - reconfigureVisibleCells() + reloadVisibleCells() } @objc func displayNameDidChange(_ note: Notification) { diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index 89ede5054..4bdfff73f 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -57,7 +57,7 @@ struct SidebarItemNode: Hashable, Sendable { private var rootSplitViewController: RootSplitViewController! private var mainFeedCollectionViewController: MainFeedCollectionViewController! - private var mainTimelineViewController: MainTimelineViewController? + private var mainTimelineViewController: MainTimelineCollectionViewController? private var articleViewController: ArticleViewController? private let fetchAndMergeArticlesQueue = CoalescingQueue(name: "Fetch and Merge Articles", interval: 0.5) @@ -314,7 +314,7 @@ struct SidebarItemNode: Hashable, Sendable { self.mainFeedCollectionViewController?.navigationController?.delegate = self updateNavigationBarSubtitles(nil) - self.mainTimelineViewController = rootSplitViewController.viewController(for: .supplementary) as? MainTimelineViewController + self.mainTimelineViewController = rootSplitViewController.viewController(for: .supplementary) as? MainTimelineCollectionViewController self.mainTimelineViewController?.coordinator = self self.mainTimelineViewController?.navigationController?.delegate = self From 442b4c02191282ca97416f00aba328dcc8d4fed1 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sat, 24 Jan 2026 23:07:06 +0800 Subject: [PATCH 03/15] additional collectionview work --- .../UIKit/UICollectionView+RSCore.swift | 2 +- iOS/Base.lproj/Main.storyboard | 211 ++++++------------ .../MainTimelineCollectionViewCell.swift | 8 +- ...MainTimelineCollectionViewController.swift | 109 ++++++++- 4 files changed, 175 insertions(+), 155 deletions(-) diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift index fd71a9829..ef25e5968 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift @@ -22,7 +22,7 @@ extension UICollectionView { return } - selectItem(at: indexPath, animated: animations.contains(.select), scrollPosition: []) + selectItem(at: indexPath, animated: true, scrollPosition: []) if !indexPathsForVisibleItems.contains(indexPath) { scrollToItem(at: indexPath, at: .centeredVertically, animated: true) diff --git a/iOS/Base.lproj/Main.storyboard b/iOS/Base.lproj/Main.storyboard index 29398c0ae..c2e788ea7 100644 --- a/iOS/Base.lproj/Main.storyboard +++ b/iOS/Base.lproj/Main.storyboard @@ -469,12 +469,12 @@ - - + + - + @@ -482,81 +482,55 @@ - + - + - - - - + + - - - - - + + - - - - - - - - - - - - - - - - - - - - - + @@ -567,81 +541,55 @@ - + - + - - - - + + - - - - - + + - - - - - - - - - - - - - - - - - - - - - + @@ -652,71 +600,62 @@ - + - - + + - + - - - - - + + - - + + - - - - - - - - - - - - - - + + + + + + + + - + @@ -726,71 +665,65 @@ - + - - + + - + - - - - - + + - - + + - - - - - - - - - - - - - - + + + + + + + + + + + - + diff --git a/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift index 579504e61..62ca21fd3 100644 --- a/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift +++ b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift @@ -197,7 +197,9 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { } func titleTextColor(for state: UICellConfigurationState) -> UIColor { - if state.isSelected { + if state.isSwiped { + return .label + } else if state.isSelected { return .white } else { return .label @@ -232,10 +234,6 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state) backgroundConfig.cornerRadius = 20 - if traitCollection.userInterfaceIdiom == .pad { - backgroundConfig.edgesAddingLayoutMarginsToBackgroundInsets = [.leading, .trailing] - backgroundConfig.backgroundInsets = NSDirectionalEdgeInsets(top: 0, leading: !isPreview ? -4 : -12, bottom: 0, trailing: !isPreview ? -4 : -12) - } if state.isSwiped { backgroundConfig.backgroundColor = .secondarySystemFill diff --git a/iOS/MainTimeline/MainTimelineCollectionViewController.swift b/iOS/MainTimeline/MainTimelineCollectionViewController.swift index b90ee42c1..46950a175 100644 --- a/iOS/MainTimeline/MainTimelineCollectionViewController.swift +++ b/iOS/MainTimeline/MainTimelineCollectionViewController.swift @@ -189,7 +189,8 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un navigationItem.largeTitleDisplayMode = .never navigationItem.titleView = navigationBarTitleLabel navigationItem.subtitleView = navigationBarSubtitleTitleLabel - + + } override func viewWillAppear(_ animated: Bool) { @@ -268,9 +269,7 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un Self.logger.debug("MainTimelineViewController: updateArticleSelection") if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { - if collectionView.indexPathsForSelectedItems?.first != indexPath { - collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: animations) - } + collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: animations) } else { collectionView.selectItem(at: nil, animated: animations.contains(.select), scrollPosition: .centeredVertically) } @@ -432,6 +431,91 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un // MARK: UICollectionViewDelegate + override func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemsAt indexPaths: [IndexPath], point: CGPoint) -> UIContextMenuConfiguration? { + guard let firstIndex = indexPaths.first, let article = dataSource.itemIdentifier(for: firstIndex) else { return nil } + + return UIContextMenuConfiguration(identifier: firstIndex.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] _ in + + guard let self = self else { return nil } + + var menuElements = [UIMenuElement]() + + var markActions = [UIAction]() + if let action = self.toggleArticleReadStatusAction(article) { + markActions.append(action) + } + markActions.append(self.toggleArticleStarStatusAction(article)) + if let action = self.markAboveAsReadAction(article, indexPath: firstIndex) { + markActions.append(action) + } + if let action = self.markBelowAsReadAction(article, indexPath: firstIndex) { + markActions.append(action) + } + menuElements.append(UIMenu(title: "", options: .displayInline, children: markActions)) + + var secondaryActions = [UIAction]() + if let action = self.discloseFeedAction(article) { + secondaryActions.append(action) + } + if let action = self.markAllInFeedAsReadAction(article, indexPath: firstIndex) { + secondaryActions.append(action) + } + if !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) + + }) + } + + override func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, highlightPreviewForItemAt indexPath: IndexPath) -> UITargetedPreview? { + guard let row = configuration.identifier as? Int, + let cell = collectionView.cellForItem(at: IndexPath(row: row, section: 0)) else { + return nil + } + + let previewView = cell.contentView + let parameters = UIPreviewParameters() + parameters.backgroundColor = .white + parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, + cornerRadius: 20) + return UITargetedPreview(view: cell, parameters: parameters) + } + + + override 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)), let _ = view.window else { + return nil + } + + let previewView = cell.contentView + let parameters = UIPreviewParameters() + parameters.backgroundColor = .white + parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, + cornerRadius: 20) + return UITargetedPreview(view: cell, parameters: parameters) + } @@ -512,7 +596,6 @@ private extension MainTimelineCollectionViewController { var config = UICollectionLayoutListConfiguration(appearance: .plain) config.showsSeparators = false config.headerMode = .none - config.trailingSwipeActionsConfigurationProvider = { [unowned self] indexPath in guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } var actions = [UIContextualAction]() @@ -589,7 +672,7 @@ private extension MainTimelineCollectionViewController { return config } config.leadingSwipeActionsConfigurationProvider = { [unowned self] indexPath in - + Self.logger.debug("Leading swipe provider called for \(indexPath.row)") guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } guard !article.status.read || article.isAvailableToMarkUnread else { return nil } var actions = [UIContextualAction]() @@ -613,11 +696,13 @@ private extension MainTimelineCollectionViewController { return config } - let layout = UICollectionViewCompositionalLayout.list(using: config) - collectionView.setCollectionViewLayout(layout, animated: false) collectionView.refreshControl = UIRefreshControl() collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) - collectionView.allowsMultipleSelection = false + collectionView.contentInsetAdjustmentBehavior = .always + + let layout = UICollectionViewCompositionalLayout.list(using: config) + layout.configuration.contentInsetsReference = .safeArea + collectionView.collectionViewLayout = layout } private func makeDataSource() -> UICollectionViewDiffableDataSource { @@ -645,7 +730,6 @@ private extension MainTimelineCollectionViewController { return cell } } - }) return dataSource @@ -733,6 +817,10 @@ private extension MainTimelineCollectionViewController { completion?() } } + + + + } @@ -1195,3 +1283,4 @@ extension MainTimelineCollectionViewController { return action } } + From 3aba6ce688411e8ee51922e5d088ff9077a3b513 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 13:56:56 +0800 Subject: [PATCH 04/15] =?UTF-8?q?=E2=9C=A8=20Timeline=20as=20CollectionVie?= =?UTF-8?q?w?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UIKit/UICollectionView+RSCore.swift | 18 + iOS/Base.lproj/Main.storyboard | 637 +++++---- .../MainTimelineCollectionViewCell.swift | 46 +- ...=> MainTimelineModernViewController.swift} | 172 ++- .../MainTimelineViewController.swift | 1224 ----------------- iOS/SceneCoordinator.swift | 4 +- 6 files changed, 491 insertions(+), 1610 deletions(-) rename iOS/MainTimeline/{MainTimelineCollectionViewController.swift => MainTimelineModernViewController.swift} (89%) delete mode 100644 iOS/MainTimeline/MainTimelineViewController.swift diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift index ef25e5968..ba82e87c2 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift @@ -12,6 +12,24 @@ import Foundation import UIKit extension UICollectionView { + /* + func selectRowAndScrollIfNotVisible(at indexPath: IndexPath, animations: Animations) { + guard let dataSource = dataSource, + let numberOfSections = dataSource.numberOfSections, + indexPath.section < numberOfSections(self), + indexPath.row < dataSource.tableView(self, numberOfRowsInSection: indexPath.section) else { + return + } + + selectRow(at: indexPath, animated: animations.contains(.select), scrollPosition: .none) + + if let visibleIndexPaths = indexPathsForRows(in: safeAreaLayoutGuide.layoutFrame) { + if !(visibleIndexPaths.contains(indexPath) && cellCompletelyVisible(indexPath)) { + scrollToRow(at: indexPath, at: .middle, animated: animations.contains(.scroll)) + } + } + } + */ /// Selects an item and scrolls it to the middle if it is not visible public func selectItemAndScrollIfNotVisible(at indexPath: IndexPath, animations: Animations) { diff --git a/iOS/Base.lproj/Main.storyboard b/iOS/Base.lproj/Main.storyboard index c2e788ea7..023e3824e 100644 --- a/iOS/Base.lproj/Main.storyboard +++ b/iOS/Base.lproj/Main.storyboard @@ -464,311 +464,378 @@ - + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + - + - + - - + + - - + + - - + + - + - + - + @@ -1207,19 +1274,25 @@ - + + + + + + + - + - + diff --git a/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift index 62ca21fd3..5af73c332 100644 --- a/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift +++ b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift @@ -15,6 +15,7 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { @IBOutlet var indicatorView: IconView! @IBOutlet var articleDate: UILabel! @IBOutlet var metaDataStackView: UIStackView! + @IBOutlet var topSeparator: UIView! var cellData: MainTimelineCellData! { didSet { @@ -63,7 +64,7 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { } UIView.animate(withDuration: 0.25) { self.indicatorView.iconImage = Assets.Images.unreadCellIndicator - self.indicatorView.tintColor = Assets.Colors.secondaryAccent + self.indicatorView.tintColor = (state.isSelected && !state.isSwiped) ? .white : Assets.Colors.secondaryAccent } return } @@ -73,7 +74,7 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { } UIView.animate(withDuration: 0.25) { self.indicatorView.iconImage = Assets.Images.starredFeed - self.indicatorView.tintColor = Assets.Colors.star + self.indicatorView.tintColor = (state.isSelected && !state.isSwiped) ? .white : Assets.Colors.star } return } @@ -105,8 +106,10 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { private func setIconImage(_ iconImage: IconImage?, with size: IconSize) { - updateIconViewSizeConstraints(to: size.size) - feedIcon!.iconImage = iconImage + if feedIcon != nil { + updateIconViewSizeConstraints(to: size.size) + feedIcon!.iconImage = iconImage + } } private func updateIconViewSizeConstraints(to size: CGSize) { @@ -197,9 +200,11 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { } func titleTextColor(for state: UICellConfigurationState) -> UIColor { - if state.isSwiped { + if state.isSwiped && state.isSelected { + return .white + } else if state.isSwiped && !state.isSelected { return .label - } else if state.isSelected { + } else if !state.isSwiped && state.isSelected { return .white } else { return .label @@ -235,20 +240,35 @@ class MainTimelineCollectionViewCell: UICollectionViewCell { var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state) backgroundConfig.cornerRadius = 20 - if state.isSwiped { - backgroundConfig.backgroundColor = .secondarySystemFill - articleContent.textColor = titleTextColor(for: state) - articleDate.textColor = .secondaryLabel - articleByLine.textColor = .secondaryLabel - } else if state.isSelected { + if traitCollection.userInterfaceIdiom == .pad { + backgroundConfig.edgesAddingLayoutMarginsToBackgroundInsets = [.leading, .trailing] + backgroundConfig.backgroundInsets = NSDirectionalEdgeInsets(top: 0, leading: !isPreview ? -12 : -12, bottom: 0, trailing: !isPreview ? -12 : -12) + } + + if state.isSwiped && state.isSelected { backgroundConfig.backgroundColor = Assets.Colors.primaryAccent articleContent.textColor = titleTextColor(for: state) articleDate.textColor = .lightText articleByLine.textColor = .lightText - } else { + topSeparator.alpha = 0.0 + } else if state.isSwiped && !state.isSelected { + backgroundConfig.backgroundColor = .secondarySystemFill articleContent.textColor = titleTextColor(for: state) articleDate.textColor = .secondaryLabel articleByLine.textColor = .secondaryLabel + topSeparator.alpha = 0.0 + } else if !state.isSwiped && state.isSelected { + backgroundConfig.backgroundColor = Assets.Colors.primaryAccent + articleContent.textColor = titleTextColor(for: state) + articleDate.textColor = .lightText + articleByLine.textColor = .lightText + topSeparator.alpha = 0.0 + } else { + backgroundConfig.backgroundColor = .clear + articleContent.textColor = titleTextColor(for: state) + articleDate.textColor = .secondaryLabel + articleByLine.textColor = .secondaryLabel + topSeparator.alpha = 1.0 } updateIndicatorView(state) diff --git a/iOS/MainTimeline/MainTimelineCollectionViewController.swift b/iOS/MainTimeline/MainTimelineModernViewController.swift similarity index 89% rename from iOS/MainTimeline/MainTimelineCollectionViewController.swift rename to iOS/MainTimeline/MainTimelineModernViewController.swift index 46950a175..278cca52b 100644 --- a/iOS/MainTimeline/MainTimelineCollectionViewController.swift +++ b/iOS/MainTimeline/MainTimelineModernViewController.swift @@ -1,8 +1,8 @@ // -// MainTimelineCollectionViewController.swift +// MainTimelineModernViewController.swift // NetNewsWire-iOS // -// Created by Stuart Breckenridge on 24/01/2026. +// Created by Stuart Breckenridge on 25/01/2026. // Copyright © 2026 Ranchero Software. All rights reserved. // @@ -19,8 +19,7 @@ let standardCellIdentifierIndex0 = "MainTimelineCellIndexZero" let standardCellIdentifierIcon = "MainTimelineCellIcon" let standardCellIdentifierIconIndex0 = "MainTimelineCellIconIndexZero" - -final class MainTimelineCollectionViewController: UICollectionViewController, UndoableCommandRunner { +class MainTimelineModernViewController: UIViewController, UndoableCommandRunner { // MARK: Private Variables private var numberOfTextLines = 0 @@ -138,30 +137,24 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un // MARK: Private Constants private let searchController = UISearchController(searchResultsController: nil) private let keyboardManager = KeyboardManager(type: .timeline) - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainTimelineCollectionViewController") + private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainTimelineModernViewController") - // MARK: Constantns + // MARK: Constants let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0) // MARK: - IBOutlets @IBOutlet var markAllAsReadButton: UIBarButtonItem? + @IBOutlet var collectionView: UICollectionView! - // MARK: - Lifecycle override func viewDidLoad() { - Self.logger.debug("MainTimelineCollectionViewController: viewDidLoad") - assert(coordinator != nil) - super.viewDidLoad() - addNotificationObservers() configureCollectionView() configureSearchController() definesPresentationContext = true - // Uncomment the following line to preserve selection between presentations - self.clearsSelectionOnViewWillAppear = false numberOfTextLines = AppDefaults.shared.timelineNumberOfLines iconSize = AppDefaults.shared.timelineIconSize @@ -189,12 +182,11 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un navigationItem.largeTitleDisplayMode = .never navigationItem.titleView = navigationBarTitleLabel navigationItem.subtitleView = navigationBarSubtitleTitleLabel - - + // Do any additional setup after loading the view. } - + override func viewWillAppear(_ animated: Bool) { - Self.logger.debug("MainTimelineViewController: viewWillAppear") + Self.logger.debug("MainTimelineModernViewController: viewWillAppear") super.viewWillAppear(animated) self.navigationController?.isToolbarHidden = false @@ -209,7 +201,7 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un } override func viewDidAppear(_ animated: Bool) { - Self.logger.debug("MainTimelineViewController: viewDidAppear") + Self.logger.debug("MainTimelineModernViewController: viewDidAppear") super.viewDidAppear(true) isTimelineViewControllerPending = false @@ -229,11 +221,18 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un } func restoreSelectionIfNecessary(adjustScroll: Bool) { + Self.logger.debug("MainTimelineModernViewController: restoreSelectionIfNecessary") if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { if adjustScroll { + Self.logger.debug("MainTimelineModernViewController: restoreSelectionIfNecessary selecting item and adjusting scroll") collectionView.selectItemAndScrollIfNotVisible(at: indexPath, animations: []) } else { - collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically) + if let indexPaths = collectionView.indexPathsForSelectedItems { + if !indexPaths.contains(indexPath) { + Self.logger.debug("MainTimelineModernViewController: restoreSelectionIfNecessary does not contain selected index path") + collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically) + } + } } } } @@ -254,21 +253,25 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un label.sizeToFit() } } - + func reinitializeArticles(resetScroll: Bool) { - Self.logger.debug("MainTimelineViewController: reinitializeArticles") + Self.logger.debug("MainTimelineModernViewController: reinitializeArticles") resetUI(resetScroll: resetScroll) } func reloadArticles(animated: Bool) { - Self.logger.debug("MainTimelineViewController: reloadArticles") + Self.logger.debug("MainTimelineModernViewController: reloadArticles") applyChanges(animated: animated) } func updateArticleSelection(animations: Animations) { - Self.logger.debug("MainTimelineViewController: updateArticleSelection") - - if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { + Self.logger.debug("MainTimelineModernViewController: updateArticleSelection") + + 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) @@ -278,7 +281,7 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un } func updateUI() { - Self.logger.debug("MainTimelineViewController: updateUI") + Self.logger.debug("MainTimelineModernViewController: updateUI") refreshProgressView?.update() updateToolbar() @@ -295,7 +298,7 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un } func focus() { - Self.logger.debug("MainTimelineViewController: focus") + Self.logger.debug("MainTimelineModernViewController: focus") becomeFirstResponder() } @@ -306,6 +309,7 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un } @objc private func reloadVisibleCells() { + Self.logger.debug("MainTimelineModernViewController: reloadVisibleCells") guard isViewLoaded, view.window != nil else { return } @@ -316,15 +320,19 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un } private func reloadCells(_ articles: [Article]) { + Self.logger.debug("MainTimelineModernViewController: reloadCells") guard !articles.isEmpty else { return } var snapshot = dataSource.snapshot() snapshot.reloadItems(articles) - dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in - self?.restoreSelectionIfNecessary(adjustScroll: false) - } + DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.0, execute: { + self.dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in + self?.restoreSelectionIfNecessary(adjustScroll: false) + } + }) + } @objc func refreshAccounts(_ sender: Any) { @@ -416,22 +424,24 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un // 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 destinationViewController]. + // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ - // MARK: UICollectionViewDataSource +} - override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + +// MARK: - UICollectionViewDelegate + +extension MainTimelineModernViewController: UICollectionViewDelegate { + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { becomeFirstResponder() let article = dataSource.itemIdentifier(for: indexPath) coordinator?.selectArticle(article, animations: [.scroll, .select, .navigation]) } - - // MARK: UICollectionViewDelegate - override func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemsAt indexPaths: [IndexPath], point: CGPoint) -> UIContextMenuConfiguration? { + func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemsAt indexPaths: [IndexPath], point: CGPoint) -> UIContextMenuConfiguration? { guard let firstIndex = indexPaths.first, let article = dataSource.itemIdentifier(for: firstIndex) else { return nil } return UIContextMenuConfiguration(identifier: firstIndex.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] _ in @@ -488,7 +498,7 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un }) } - override func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, highlightPreviewForItemAt indexPath: IndexPath) -> UITargetedPreview? { + func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, highlightPreviewForItemAt indexPath: IndexPath) -> UITargetedPreview? { guard let row = configuration.identifier as? Int, let cell = collectionView.cellForItem(at: IndexPath(row: row, section: 0)) else { return nil @@ -503,7 +513,7 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un } - override func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, dismissalPreviewForItemAt indexPath: IndexPath) -> UITargetedPreview? { + 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)), let _ = view.window else { return nil @@ -516,36 +526,10 @@ final class MainTimelineCollectionViewController: UICollectionViewController, Un cornerRadius: 20) return UITargetedPreview(view: cell, parameters: parameters) } - - - - /* - // Uncomment this method to specify if the specified item should be selected - override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { - return true - } - */ - - /* - // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item - override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { - return false - } - - override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { - return false - } - - override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { - - } - */ - } - // MARK: Private API -private extension MainTimelineCollectionViewController { +private extension MainTimelineModernViewController { func addNotificationObservers() { NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) @@ -606,7 +590,14 @@ private extension MainTimelineCollectionViewController { NSLocalizedString("Star", comment: "Star") let starAction = UIContextualAction(style: .normal, title: starTitle) { [weak self] _, _, completion in - self?.toggleStar(article) + /// The call to `toggleStar` is delayed in order to allow + /// the swipe animation to complete. Calling `toggleStar` with no + /// delay results UICollectionView internal inconsistency: unexpected + /// removal of the current swipe occurrence's mask view error. + DispatchQueue.main.asyncAfter(deadline: .now() + 0.85, execute: { + self?.toggleStar(article) + }) + completion(true) } @@ -672,7 +663,6 @@ private extension MainTimelineCollectionViewController { return config } config.leadingSwipeActionsConfigurationProvider = { [unowned self] indexPath in - Self.logger.debug("Leading swipe provider called for \(indexPath.row)") guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } guard !article.status.read || article.isAvailableToMarkUnread else { return nil } var actions = [UIContextualAction]() @@ -683,7 +673,13 @@ private extension MainTimelineCollectionViewController { NSLocalizedString("Mark as Read", comment: "Mark as Read") let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] _, _, completion in - self?.toggleRead(article) + /// The call to `toggleRead` is delayed in order to allow + /// the swipe animation to complete. Calling `toggleRead` with no + /// delay results UICollectionView internal inconsistency: unexpected + /// removal of the current swipe occurrence's mask view error. + DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.85, execute: { + self?.toggleRead(article) + }) completion(true) } @@ -692,7 +688,7 @@ private extension MainTimelineCollectionViewController { actions.append(readAction) let config = UISwipeActionsConfiguration(actions: actions) - config.performsFirstActionWithFullSwipe = false + config.performsFirstActionWithFullSwipe = true return config } @@ -702,7 +698,7 @@ private extension MainTimelineCollectionViewController { let layout = UICollectionViewCompositionalLayout.list(using: config) layout.configuration.contentInsetsReference = .safeArea - collectionView.collectionViewLayout = layout + collectionView.collectionViewLayout = layout } private func makeDataSource() -> UICollectionViewDiffableDataSource { @@ -725,7 +721,7 @@ private extension MainTimelineCollectionViewController { cell.cellData = cellData return cell } else { - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifier, for: indexPath) as! MainTimelineCollectionViewCell + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifier, for: indexPath) as! MainTimelineCollectionViewCell cell.cellData = cellData return cell } @@ -808,6 +804,7 @@ private extension MainTimelineCollectionViewController { } func applyChanges(animated: Bool, completion: (() -> Void)? = nil) { + Self.logger.debug("MainTimelineModernViewController: applyChanges") var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([0]) snapshot.appendItems(articles ?? ArticleArray(), toSection: 0) @@ -824,17 +821,15 @@ private extension MainTimelineCollectionViewController { } - - // MARK: - Notifications API -private extension MainTimelineCollectionViewController { +private extension MainTimelineModernViewController { @objc dynamic func unreadCountDidChange(_ notification: Notification) { - Self.logger.debug("MainTimelineViewController: unreadCountDidChange") + Self.logger.debug("MainTimelineModernViewController: unreadCountDidChange") updateUI() } @objc func statusesDidChange(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: statusesDidChange") + Self.logger.debug("MainTimelineModernViewController: statusesDidChange") guard isViewLoaded, view.window != nil else { return @@ -853,7 +848,7 @@ private extension MainTimelineCollectionViewController { } @objc func feedIconDidBecomeAvailable(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: feedIconDidBecomeAvailable") + Self.logger.debug("MainTimelineModernViewController: feedIconDidBecomeAvailable") guard isViewLoaded, view.window != nil else { return @@ -866,7 +861,7 @@ private extension MainTimelineCollectionViewController { } @objc func avatarDidBecomeAvailable(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: avatarDidBecomeAvailable") + Self.logger.debug("MainTimelineModernViewController: avatarDidBecomeAvailable") guard isViewLoaded, view.window != nil else { return @@ -893,7 +888,7 @@ private extension MainTimelineCollectionViewController { } @objc func faviconDidBecomeAvailable(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: faviconDidBecomeAvailable") + Self.logger.debug("MainTimelineModernViewController: faviconDidBecomeAvailable") guard isViewLoaded, view.window != nil else { return @@ -925,7 +920,7 @@ private extension MainTimelineCollectionViewController { } func userDefaultsDidChange() { - Self.logger.debug("MainTimelineViewController: userDefaultsDidChange") + Self.logger.debug("MainTimelineModernViewController: userDefaultsDidChange") if self.numberOfTextLines != AppDefaults.shared.timelineNumberOfLines || self.iconSize != AppDefaults.shared.timelineIconSize { self.numberOfTextLines = AppDefaults.shared.timelineNumberOfLines @@ -936,29 +931,28 @@ private extension MainTimelineCollectionViewController { } @objc func contentSizeCategoryDidChange(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: contentSizeCategoryDidChange") + Self.logger.debug("MainTimelineModernViewController: contentSizeCategoryDidChange") reloadVisibleCells() } @objc func displayNameDidChange(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: displayNameDidChange") + Self.logger.debug("MainTimelineModernViewController: displayNameDidChange") updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "") } @objc func willEnterForeground(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: willEnterForeground") + Self.logger.debug("MainTimelineModernViewController: willEnterForeground") updateUI() } @objc func scrollPositionDidChange() { - Self.logger.debug("MainTimelineViewController: scrollPositionDidChange") + Self.logger.debug("MainTimelineModernViewController: scrollPositionDidChange") timelineMiddleIndexPath = collectionView.middleVisibleRow() } } - -extension MainTimelineCollectionViewController: UISearchControllerDelegate { +extension MainTimelineModernViewController: UISearchControllerDelegate { func willPresentSearchController(_ searchController: UISearchController) { coordinator?.beginSearching() @@ -973,7 +967,7 @@ extension MainTimelineCollectionViewController: UISearchControllerDelegate { } -extension MainTimelineCollectionViewController: UISearchResultsUpdating { +extension MainTimelineModernViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { let searchScope = SearchScope(rawValue: searchController.searchBar.selectedScopeButtonIndex)! @@ -982,7 +976,7 @@ extension MainTimelineCollectionViewController: UISearchResultsUpdating { } -extension MainTimelineCollectionViewController: UISearchBarDelegate { +extension MainTimelineModernViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { let searchScope = SearchScope(rawValue: selectedScope)! searchArticles(searchBar.text!, searchScope) @@ -990,7 +984,7 @@ extension MainTimelineCollectionViewController: UISearchBarDelegate { } // MARK: Article Actions -extension MainTimelineCollectionViewController { +extension MainTimelineModernViewController { func toggleRead(_ article: Article) { assert(coordinator != nil) coordinator?.toggleRead(article) diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift deleted file mode 100644 index 1429ced18..000000000 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ /dev/null @@ -1,1224 +0,0 @@ -// -// MainTimelineViewController.swift -// NetNewsWire -// -// Created by Maurice Parker on 4/8/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit -import os -import WebKit -import RSCore -import RSWeb -import Account -import Articles - -//let standardCellIdentifier = "MainTimelineCellStandard" -//let standardCellIdentifierIndex0 = "MainTimelineCellIndexZero" -//let standardCellIdentifierIcon = "MainTimelineCellIcon" -//let standardCellIdentifierIconIndex0 = "MainTimelineCellIconIndexZero" - -final class MainTimelineViewController: UITableViewController, UndoableCommandRunner { - - private var numberOfTextLines = 0 - private var iconSize = IconSize.medium - private lazy var feedTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) - - private var refreshProgressView: RefreshProgressView? - - @IBOutlet var markAllAsReadButton: UIBarButtonItem? - - private lazy var filterButton = UIBarButtonItem(image: Assets.Images.filter, style: .plain, target: self, action: #selector(toggleFilter(_:))) - private lazy var firstUnreadButton = UIBarButtonItem(image: Assets.Images.nextUnread, style: .plain, target: self, action: #selector(firstUnread(_:))) - - private lazy var dataSource = makeDataSource() - private let searchController = UISearchController(searchResultsController: nil) - - weak var coordinator: SceneCoordinator? - var undoableCommands = [UndoableCommand]() - let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0) - - private var timelineFeed: SidebarItem? { - assert(coordinator != nil) - return coordinator?.timelineFeed - } - - private var showIcons: Bool { - assert(coordinator != nil) - return coordinator?.showIcons ?? false - } - - private var currentArticle: Article? { - assert(coordinator != nil) - return coordinator?.currentArticle - } - - private var timelineMiddleIndexPath: IndexPath? { - get { - coordinator?.timelineMiddleIndexPath - } - set { - coordinator?.timelineMiddleIndexPath = newValue - } - } - - private var isTimelineViewControllerPending: Bool { - get { - coordinator?.isTimelineViewControllerPending ?? false - } - set { - coordinator?.isTimelineViewControllerPending = newValue - } - } - - private var timelineIconImage: IconImage? { - assert(coordinator != nil) - return coordinator?.timelineIconImage - } - - private var timelineDefaultReadFilterType: ReadFilterType { - return timelineFeed?.defaultReadFilterType ?? .none - } - - private var isReadArticlesFiltered: Bool { - assert(coordinator != nil) - return coordinator?.isReadArticlesFiltered ?? false - } - - private var isTimelineUnreadAvailable: Bool { - assert(coordinator != nil) - return coordinator?.isTimelineUnreadAvailable ?? false - } - - private var isRootSplitCollapsed: Bool { - assert(coordinator != nil) - return coordinator?.isRootSplitCollapsed ?? false - } - - private var articles: ArticleArray? { - assert(coordinator != nil) - return coordinator?.articles - } - - private let keyboardManager = KeyboardManager(type: .timeline) - override var keyCommands: [UIKeyCommand]? { - - // If the first responder is the WKWebView (PreloadedWebView) we don't want to supply any keyboard - // commands that the system is looking for by going up the responder chain. They will interfere with - // the WKWebViews built in hardware keyboard shortcuts, specifically the up and down arrow keys. - guard let current = UIResponder.currentFirstResponder, !(current is PreloadedWebView) else { return nil } - - return keyboardManager.keyCommands - } - - private lazy var navigationBarTitleLabel: UILabel = { - let label = UILabel() - label.font = UIFont.preferredFont(forTextStyle: .subheadline).bold() - label.isUserInteractionEnabled = true - label.numberOfLines = 1 - label.textAlignment = .center - label.adjustsFontForContentSizeCategory = false - let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) - label.addGestureRecognizer(tap) - let pointerInteraction = UIPointerInteraction(delegate: nil) - label.addInteraction(pointerInteraction) - return label - }() - - private lazy var navigationBarSubtitleTitleLabel: UILabel = { - let label = UILabel() - label.font = UIFont(name: "Helvetica", size: 12) - label.textColor = .systemGray - label.textAlignment = .center - label.isUserInteractionEnabled = true - label.adjustsFontForContentSizeCategory = false - let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) - label.addGestureRecognizer(tap) - return label - }() - - override var canBecomeFirstResponder: Bool { - true - } - - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainTimelineViewController") - - override func viewDidLoad() { - Self.logger.debug("MainTimelineViewController: viewDidLoad") - - assert(coordinator != nil) - - super.viewDidLoad() - - 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(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in - Task { @MainActor in - self?.userDefaultsDidChange() - } - } - 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) - - // Setup the Search Controller - searchController.delegate = self - searchController.searchResultsUpdater = self - searchController.obscuresBackgroundDuringPresentation = false - searchController.searchBar.delegate = self - searchController.searchBar.placeholder = NSLocalizedString("Search Articles", comment: "Search Articles") - searchController.searchBar.scopeButtonTitles = [ - NSLocalizedString("Here", comment: "Here"), - NSLocalizedString("All Articles", comment: "All Articles") - ] - searchController.searchBar.barTintColor = .clear - searchController.searchBar.scopeBarBackgroundImage = UIImage() - searchController.searchBar.autocapitalizationType = .none - navigationItem.searchController = searchController - - if traitCollection.userInterfaceIdiom == .pad { - searchController.searchBar.selectedScopeButtonIndex = 1 - navigationItem.searchBarPlacementAllowsExternalIntegration = true - } - definesPresentationContext = true - - // Configure the table - tableView.dataSource = dataSource - tableView.isPrefetchingEnabled = false - - numberOfTextLines = AppDefaults.shared.timelineNumberOfLines - iconSize = AppDefaults.shared.timelineIconSize - - refreshControl = UIRefreshControl() - refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) - - configureToolbar() - resetUI(resetScroll: true) - - // Load the table and then scroll to the saved position if available - applyChanges(animated: false) { - if let restoreIndexPath = self.timelineMiddleIndexPath { - self.tableView.scrollToRow(at: restoreIndexPath, at: .middle, 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.titleView = navigationBarTitleLabel - navigationItem.subtitleView = navigationBarSubtitleTitleLabel - } - - 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 - } - - updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "") - coordinator?.updateNavigationBarSubtitles(nil) - } - - override func viewDidAppear(_ animated: Bool) { - Self.logger.debug("MainTimelineViewController: viewDidAppear") - - super.viewDidAppear(true) - isTimelineViewControllerPending = false - if navigationController?.navigationBar.alpha == 0 { - UIView.animate(withDuration: 0.5) { - self.navigationController?.navigationBar.alpha = 1 - } - } - if traitCollection.userInterfaceIdiom == .phone { - if coordinator?.currentArticle != nil { - if let indexPath = tableView.indexPathForSelectedRow { - tableView.deselectRow(at: indexPath, animated: true) - } - coordinator?.selectArticle(nil) - } - } - } - - // MARK: - Actions - - @objc func openInBrowser(_ sender: Any?) { - assert(coordinator != nil) - coordinator?.showBrowserForCurrentArticle() - } - - @objc func openInAppBrowser(_ sender: Any?) { - assert(coordinator != nil) - coordinator?.showInAppBrowser() - } - - @IBAction func toggleFilter(_ sender: Any) { - assert(coordinator != nil) - coordinator?.toggleReadArticlesFilter() - } - - private func markAllAsReadInTimeline() { - assert(coordinator != nil) - coordinator?.markAllAsReadInTimeline() - } - - @IBAction func markAllAsRead(_ sender: Any?) { - let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read") - - if let source = sender as? UIBarButtonItem { - MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: source) { [weak self] in - self?.markAllAsReadInTimeline() - } - } - - if sender is UIKeyCommand { - guard let indexPath = tableView.indexPathForSelectedRow, let contentView = tableView.cellForRow(at: indexPath)?.contentView else { - return - } - - MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in - self?.markAllAsReadInTimeline() - } - } - } - - @IBAction func firstUnread(_ sender: Any) { - assert(coordinator != nil) - coordinator?.selectFirstUnread() - } - - @objc func refreshAccounts(_ sender: Any) { - 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: - API - - func restoreSelectionIfNecessary(adjustScroll: Bool) { - if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { - if adjustScroll { - tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: []) - } else { - tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) - } - } - } - - func updateNavigationBarTitle(_ text: String) { - navigationItem.title = text - if let label = navigationItem.titleView as? UILabel { - label.text = text - label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) - label.sizeToFit() - } - } - - func updateNavigationBarSubtitle(_ text: String) { - if let label = navigationItem.subtitleView as? UILabel { - label.text = text - label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) - label.sizeToFit() - } - } - - func reinitializeArticles(resetScroll: Bool) { - Self.logger.debug("MainTimelineViewController: reinitializeArticles") - resetUI(resetScroll: resetScroll) - } - - func reloadArticles(animated: Bool) { - Self.logger.debug("MainTimelineViewController: reloadArticles") - applyChanges(animated: animated) - } - - func updateArticleSelection(animations: Animations) { - Self.logger.debug("MainTimelineViewController: updateArticleSelection") - - if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { - if tableView.indexPathForSelectedRow != indexPath { - tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: animations) - } - } else { - tableView.selectRow(at: nil, animated: animations.contains(.select), scrollPosition: .none) - } - - updateUI() - } - - func updateUI() { - Self.logger.debug("MainTimelineViewController: updateUI") - - refreshProgressView?.update() - updateToolbar() - } - - func hideSearch() { - navigationItem.searchController?.isActive = false - } - - func showSearchAll() { - navigationItem.searchController?.isActive = true - navigationItem.searchController?.searchBar.selectedScopeButtonIndex = 1 - navigationItem.searchController?.searchBar.becomeFirstResponder() - } - - func focus() { - Self.logger.debug("MainTimelineViewController: focus") - becomeFirstResponder() - } - - // MARK: - Table view - - override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { - guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - guard !article.status.read || article.isAvailableToMarkUnread else { return nil } - - // Set up the read action - let readTitle = article.status.read ? - NSLocalizedString("Mark as Unread", comment: "Mark as Unread") : - NSLocalizedString("Mark as Read", comment: "Mark as Read") - - let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] _, _, completion in - self?.toggleRead(article) - completion(true) - } - - readAction.image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen - readAction.backgroundColor = Assets.Colors.primaryAccent - - return UISwipeActionsConfiguration(actions: [readAction]) - } - - override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { - - guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - - // 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 - 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") - alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel) { _ in - completion(true) - }) - - self.present(alert, animated: true) - - } - - } - - moreAction.image = Assets.Images.more - moreAction.backgroundColor = UIColor.systemGray - - return UISwipeActionsConfiguration(actions: [starAction, moreAction]) - - } - - override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { - - guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - - return UIContextMenuConfiguration(identifier: indexPath.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] _ in - - guard let self = self else { return nil } - - var menuElements = [UIMenuElement]() - - var markActions = [UIAction]() - if let action = self.toggleArticleReadStatusAction(article) { - markActions.append(action) - } - markActions.append(self.toggleArticleStarStatusAction(article)) - if let action = self.markAboveAsReadAction(article, indexPath: indexPath) { - markActions.append(action) - } - if let action = self.markBelowAsReadAction(article, indexPath: indexPath) { - 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: indexPath) { - 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: indexPath) { - menuElements.append(UIMenu(title: "", options: .displayInline, children: [action])) - } - - return UIMenu(title: "", children: menuElements) - - }) - - } - - override func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { - guard let row = configuration.identifier as? Int, - let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) else { - return nil - } - - let previewView = cell.contentView - let parameters = UIPreviewParameters() - parameters.backgroundColor = .white - parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, - cornerRadius: 20) - return UITargetedPreview(view: cell, parameters: parameters) - } - - override func tableView(_ tableView: UITableView, previewForDismissingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { - guard let row = configuration.identifier as? Int, - let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)), let _ = view.window else { - return nil - } - - let previewView = cell.contentView - let parameters = UIPreviewParameters() - parameters.backgroundColor = .white - parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, - cornerRadius: 20) - return UITargetedPreview(view: cell, parameters: parameters) - - } - - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - becomeFirstResponder() - let article = dataSource.itemIdentifier(for: indexPath) - coordinator?.selectArticle(article, animations: [.scroll, .select, .navigation]) - } - - override func scrollViewDidScroll(_ scrollView: UIScrollView) { - scrollPositionQueue.add(self, #selector(scrollPositionDidChange)) - } - - // MARK: - Notifications - - @objc dynamic func unreadCountDidChange(_ notification: Notification) { - Self.logger.debug("MainTimelineViewController: unreadCountDidChange") - updateUI() - } - - @objc func statusesDidChange(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: statusesDidChange") - - guard isViewLoaded, view.window != nil else { - return - } - guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set, !articleIDs.isEmpty else { - return - } - guard let indexPaths = tableView.indexPathsForVisibleRows else { - return - } - - let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } - let visibleUpdatedArticles = visibleArticles.filter { articleIDs.contains($0.articleID) } - reconfigureCells(visibleUpdatedArticles) - } - - @objc func feedIconDidBecomeAvailable(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: feedIconDidBecomeAvailable") - - guard isViewLoaded, view.window != nil else { - return - } - guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed else { - return - } - - updateIconForVisibleArticles(feed) - } - - @objc func avatarDidBecomeAvailable(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: avatarDidBecomeAvailable") - - guard isViewLoaded, view.window != nil else { - return - } - guard showIcons, let avatarURL = note.userInfo?[UserInfoKey.url] as? String else { - return - } - guard let indexPaths = tableView.indexPathsForVisibleRows else { - return - } - - let articlesToReload = indexPaths.compactMap { indexPath -> Article? in - guard let article = dataSource.itemIdentifier(for: indexPath), - let authors = article.authors, - !authors.isEmpty else { - return nil - } - for author in authors { - if author.avatarURL == avatarURL { - return article - } - } - return nil - } - reconfigureCells(articlesToReload) - } - - @objc func faviconDidBecomeAvailable(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: faviconDidBecomeAvailable") - - guard isViewLoaded, view.window != nil else { - return - } - - updateIconForVisibleArticles() - } - - /// Update icon for all visible articles — or, if feed is non-nil, update articles only from that feed. - private func updateIconForVisibleArticles(_ feed: Feed? = nil) { - guard isViewLoaded, view.window != nil else { - return - } - guard showIcons else { - return - } - guard let indexPaths = tableView.indexPathsForVisibleRows else { - return - } - - let articlesToReload = indexPaths.compactMap { indexPath -> Article? in - guard let article = dataSource.itemIdentifier(for: indexPath) else { - return nil - } - if feed == nil || feed == article.feed { - return article - } - return nil - } - reconfigureCells(articlesToReload) - } - - func userDefaultsDidChange() { - Self.logger.debug("MainTimelineViewController: userDefaultsDidChange") - - if self.numberOfTextLines != AppDefaults.shared.timelineNumberOfLines || self.iconSize != AppDefaults.shared.timelineIconSize { - self.numberOfTextLines = AppDefaults.shared.timelineNumberOfLines - self.iconSize = AppDefaults.shared.timelineIconSize - self.reconfigureVisibleCells() - } - self.updateToolbar() - } - - @objc func contentSizeCategoryDidChange(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: contentSizeCategoryDidChange") - reconfigureVisibleCells() - } - - @objc func displayNameDidChange(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: displayNameDidChange") - updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "") - } - - @objc func willEnterForeground(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: willEnterForeground") - updateUI() - } - - @objc func scrollPositionDidChange() { - Self.logger.debug("MainTimelineViewController: scrollPositionDidChange") - timelineMiddleIndexPath = tableView.middleVisibleRow() - } - - // MARK: - Reloading - - func queueReloadAvailableCells() { - CoalescingQueue.standard.add(self, #selector(reconfigureVisibleCells)) - } - - @objc private func reconfigureVisibleCells() { - guard isViewLoaded, view.window != nil else { - return - } - guard let indexPaths = tableView.indexPathsForVisibleRows else { - return - } - - let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } - reconfigureCells(visibleArticles) - } - - private func reconfigureCells(_ articles: [Article]) { - guard !articles.isEmpty else { - return - } - - var snapshot = dataSource.snapshot() - snapshot.reconfigureItems(articles) - dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in - self?.restoreSelectionIfNecessary(adjustScroll: false) - } - } -} - -// MARK: Searching - -extension MainTimelineViewController: UISearchControllerDelegate { - - func willPresentSearchController(_ searchController: UISearchController) { - coordinator?.beginSearching() - searchController.searchBar.showsScopeBar = true - } - - func willDismissSearchController(_ searchController: UISearchController) { - coordinator?.endSearching() - searchController.searchBar.showsScopeBar = false - 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: Private - -private extension MainTimelineViewController { - - func searchArticles(_ searchString: String, _ searchScope: SearchScope) { - assert(coordinator != nil) - coordinator?.searchArticles(searchString, searchScope) - } - - func configureToolbar() { - if traitCollection.userInterfaceIdiom == .phone { - toolbarItems?.insert(.flexibleSpace(), at: 1) - toolbarItems?.insert(navigationItem.searchBarPlacementBarButtonItem, at: 2) - } - } - - func resetUI(resetScroll: Bool) { - let shouldShowFilterButton = coordinator?.shouldShowFilterButton() ?? false - navigationItem.rightBarButtonItem = shouldShowFilterButton ? filterButton : nil - - if isReadArticlesFiltered { - filterButton.style = .prominent - filterButton.tintColor = Assets.Colors.primaryAccent - filterButton.accLabelText = NSLocalizedString("Selected - Filter Read Articles", comment: "Selected - Filter Read Articles") - } else { - filterButton.style = .plain - filterButton.tintColor = nil - filterButton.accLabelText = NSLocalizedString("Filter Read Articles", comment: "Filter Read Articles") - } - - tableView.selectRow(at: nil, animated: false, scrollPosition: .top) - - if resetScroll { - let snapshot = dataSource.snapshot() - if snapshot.sectionIdentifiers.count > 0 && snapshot.itemIdentifiers(inSection: 0).count > 0 { - tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false) - } - } - - updateToolbar() - } - - func updateToolbar() { - markAllAsReadButton?.isEnabled = isTimelineUnreadAvailable - firstUnreadButton.isEnabled = coordinator?.isAnyUnreadAvailable ?? false - - if isRootSplitCollapsed { - if let toolbarItems = toolbarItems, toolbarItems.last != firstUnreadButton { - var items = toolbarItems - items.append(firstUnreadButton) - setToolbarItems(items, animated: false) - } - } else { - if let toolbarItems = toolbarItems, toolbarItems.last == firstUnreadButton { - let items = Array(toolbarItems[0.. Void)? = nil) { - if (articles?.count ?? 0) == 0 { - tableView.rowHeight = tableView.estimatedRowHeight - } else { - tableView.rowHeight = UITableView.automaticDimension - } - - var snapshot = NSDiffableDataSourceSnapshot() - snapshot.appendSections([0]) - snapshot.appendItems(articles ?? ArticleArray(), toSection: 0) - - dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in - self?.restoreSelectionIfNecessary(adjustScroll: false) - completion?() - } - } - - func makeDataSource() -> UITableViewDiffableDataSource { - let dataSource: UITableViewDiffableDataSource = - MainTimelineDataSource(tableView: tableView, cellProvider: { [weak self] tableView, indexPath, article in - let cellData = self!.configure(article: article) - if self!.showIcons { - if indexPath.row == 0 { - let cell = tableView.dequeueReusableCell(withIdentifier: standardCellIdentifierIconIndex0, for: indexPath) as! MainTimelineCell - cell.cellData = cellData - return cell - } else { - let cell = tableView.dequeueReusableCell(withIdentifier: standardCellIdentifierIcon, for: indexPath) as! MainTimelineCell - cell.cellData = cellData - return cell - } - } else { - if indexPath.row == 0 { - let cell = tableView.dequeueReusableCell(withIdentifier: standardCellIdentifierIndex0, for: indexPath) as! MainTimelineCell - cell.cellData = cellData - return cell - } else { - let cell = tableView.dequeueReusableCell(withIdentifier: standardCellIdentifier, for: indexPath) as! MainTimelineCell - cell.cellData = cellData - return cell - } - } - - }) - dataSource.defaultRowAnimation = .middle - return dataSource - } - - @discardableResult - 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 - } - - func iconImageFor(_ article: Article) -> IconImage? { - if !showIcons { - return nil - } - return article.iconImage() - } - - 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: "Mark as Unread") : - NSLocalizedString("Mark as Read", comment: "Mark as Read") - let image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen - - let action = UIAction(title: title, image: image) { [weak self] _ in - 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: "Mark as Unstarred") : - NSLocalizedString("Mark as Starred", comment: "Mark as Starred") - let image = article.status.starred ? Assets.Images.starOpen : Assets.Images.starClosed - - let action = UIAction(title: title, image: image) { [weak self] _ in - 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 contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let title = NSLocalizedString("Mark Above as Read", comment: "Mark Above as Read") - 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? { - guard canMarkBelowAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let title = NSLocalizedString("Mark Below as Read", comment: "Mark Below as Read") - 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? { - guard canMarkAboveAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let title = NSLocalizedString("Mark Above as Read", comment: "Mark Above as Read") - 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? { - guard canMarkBelowAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let title = NSLocalizedString("Mark Below as Read", comment: "Mark Below as Read") - 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?.markAllAsRead(articles) - } - - func markAllInFeedAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? { - guard let feed = article.feed else { return nil } - guard let fetchedArticles = try? feed.fetchArticles() else { - return nil - } - - let articles = Array(fetchedArticles) - guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(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, 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 { return nil } - guard let fetchedArticles = try? feed.fetchArticles() else { - return nil - } - - let articles = Array(fetchedArticles) - guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Mark All as Read in Feed") - 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: "Copy Article URL") - 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: "Copy External URL") - 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: "Open in Browser") - 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: "Open in Browser") - 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 cell = tableView.cellForRow(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") - 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") - let action = UIAlertAction(title: title, style: .default) { [weak self] _ in - completion(true) - self?.shareDialogForTableCell(indexPath: indexPath, url: url, title: article.title) - } - return action - } - -} diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index 4bdfff73f..463bc93e4 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -57,7 +57,7 @@ struct SidebarItemNode: Hashable, Sendable { private var rootSplitViewController: RootSplitViewController! private var mainFeedCollectionViewController: MainFeedCollectionViewController! - private var mainTimelineViewController: MainTimelineCollectionViewController? + private var mainTimelineViewController: MainTimelineModernViewController? private var articleViewController: ArticleViewController? private let fetchAndMergeArticlesQueue = CoalescingQueue(name: "Fetch and Merge Articles", interval: 0.5) @@ -314,7 +314,7 @@ struct SidebarItemNode: Hashable, Sendable { self.mainFeedCollectionViewController?.navigationController?.delegate = self updateNavigationBarSubtitles(nil) - self.mainTimelineViewController = rootSplitViewController.viewController(for: .supplementary) as? MainTimelineCollectionViewController + self.mainTimelineViewController = rootSplitViewController.viewController(for: .supplementary) as? MainTimelineModernViewController self.mainTimelineViewController?.coordinator = self self.mainTimelineViewController?.navigationController?.delegate = self From c0d35af0648f579b6ab7a0d1b6cee5349c38c31d Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 14:00:21 +0800 Subject: [PATCH 05/15] =?UTF-8?q?=F0=9F=94=A5=20Delete=20comments?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RSCore/UIKit/UICollectionView+RSCore.swift | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift index ba82e87c2..ef25e5968 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift @@ -12,24 +12,6 @@ import Foundation import UIKit extension UICollectionView { - /* - func selectRowAndScrollIfNotVisible(at indexPath: IndexPath, animations: Animations) { - guard let dataSource = dataSource, - let numberOfSections = dataSource.numberOfSections, - indexPath.section < numberOfSections(self), - indexPath.row < dataSource.tableView(self, numberOfRowsInSection: indexPath.section) else { - return - } - - selectRow(at: indexPath, animated: animations.contains(.select), scrollPosition: .none) - - if let visibleIndexPaths = indexPathsForRows(in: safeAreaLayoutGuide.layoutFrame) { - if !(visibleIndexPaths.contains(indexPath) && cellCompletelyVisible(indexPath)) { - scrollToRow(at: indexPath, at: .middle, animated: animations.contains(.scroll)) - } - } - } - */ /// Selects an item and scrolls it to the middle if it is not visible public func selectItemAndScrollIfNotVisible(at indexPath: IndexPath, animations: Animations) { From f56c978679253873f8e7df63a27ad774430f69fc Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 14:03:30 +0800 Subject: [PATCH 06/15] =?UTF-8?q?=F0=9F=93=9D=20mark=20class=20final?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iOS/MainTimeline/MainTimelineModernViewController.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iOS/MainTimeline/MainTimelineModernViewController.swift b/iOS/MainTimeline/MainTimelineModernViewController.swift index 278cca52b..4e69869b0 100644 --- a/iOS/MainTimeline/MainTimelineModernViewController.swift +++ b/iOS/MainTimeline/MainTimelineModernViewController.swift @@ -19,7 +19,7 @@ let standardCellIdentifierIndex0 = "MainTimelineCellIndexZero" let standardCellIdentifierIcon = "MainTimelineCellIcon" let standardCellIdentifierIconIndex0 = "MainTimelineCellIconIndexZero" -class MainTimelineModernViewController: UIViewController, UndoableCommandRunner { +final class MainTimelineModernViewController: UIViewController, UndoableCommandRunner { // MARK: Private Variables private var numberOfTextLines = 0 From d1d94372f70ac10a55391a70b7f5e3f12a205d5b Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 14:08:03 +0800 Subject: [PATCH 07/15] =?UTF-8?q?=F0=9F=93=9D=20Tidy=20up?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MainTimelineModernViewController.swift | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/iOS/MainTimeline/MainTimelineModernViewController.swift b/iOS/MainTimeline/MainTimelineModernViewController.swift index 4e69869b0..8482a0f59 100644 --- a/iOS/MainTimeline/MainTimelineModernViewController.swift +++ b/iOS/MainTimeline/MainTimelineModernViewController.swift @@ -14,12 +14,14 @@ import RSWeb import Account import Articles -let standardCellIdentifier = "MainTimelineCellStandard" -let standardCellIdentifierIndex0 = "MainTimelineCellIndexZero" -let standardCellIdentifierIcon = "MainTimelineCellIcon" -let standardCellIdentifierIconIndex0 = "MainTimelineCellIconIndexZero" - final class MainTimelineModernViewController: UIViewController, UndoableCommandRunner { + + struct CellIdentifier { + static let standard = "MainTimelineCellStandard" + static let standardIndex0 = "MainTimelineCellIndexZero" + static let icon = "MainTimelineCellIcon" + static let iconIndex0 = "MainTimelineCellIconIndexZero" + } // MARK: Private Variables private var numberOfTextLines = 0 @@ -707,21 +709,21 @@ private extension MainTimelineModernViewController { let cellData = self!.configure(article: article) if self!.showIcons { if indexPath.row == 0 { - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifierIconIndex0, for: indexPath) as! MainTimelineCollectionViewCell + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier.iconIndex0, for: indexPath) as! MainTimelineCollectionViewCell cell.cellData = cellData return cell } else { - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifierIcon, for: indexPath) as! MainTimelineCollectionViewCell + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier.icon, for: indexPath) as! MainTimelineCollectionViewCell cell.cellData = cellData return cell } } else { if indexPath.row == 0 { - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifierIndex0, for: indexPath) as! MainTimelineCollectionViewCell + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier.standardIndex0, for: indexPath) as! MainTimelineCollectionViewCell cell.cellData = cellData return cell } else { - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: standardCellIdentifier, for: indexPath) as! MainTimelineCollectionViewCell + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier.standard, for: indexPath) as! MainTimelineCollectionViewCell cell.cellData = cellData return cell } From cc6b6de1258f467fd05b694fcbb0d08808e6ae38 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 14:08:34 +0800 Subject: [PATCH 08/15] old file --- .../MainTimelineViewController.swift | 1232 +++++++++++++++++ 1 file changed, 1232 insertions(+) create mode 100644 iOS/MainTimeline/MainTimelineViewController.swift diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift new file mode 100644 index 000000000..aa780bd20 --- /dev/null +++ b/iOS/MainTimeline/MainTimelineViewController.swift @@ -0,0 +1,1232 @@ +// +// MainTimelineViewController.swift +// NetNewsWire +// +// Created by Stuart Breckenridge on 25/01/2026. +// Copyright © 2026 Ranchero Software. All rights reserved. +// + + +// +// MainTimelineViewController.swift +// NetNewsWire +// +// Created by Maurice Parker on 4/8/19. +// Copyright © 2019 Ranchero Software. All rights reserved. +// + +import UIKit +import os +import WebKit +import RSCore +import RSWeb +import Account +import Articles + +final class MainTimelineViewController: UITableViewController, UndoableCommandRunner { + struct CellIdentifier { + static let standard = "MainTimelineCellStandard" + static let standardIndex0 = "MainTimelineCellIndexZero" + static let icon = "MainTimelineCellIcon" + static let iconIndex0 = "MainTimelineCellIconIndexZero" + } + + private var numberOfTextLines = 0 + private var iconSize = IconSize.medium + private lazy var feedTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) + + private var refreshProgressView: RefreshProgressView? + + @IBOutlet var markAllAsReadButton: UIBarButtonItem? + + private lazy var filterButton = UIBarButtonItem(image: Assets.Images.filter, style: .plain, target: self, action: #selector(toggleFilter(_:))) + private lazy var firstUnreadButton = UIBarButtonItem(image: Assets.Images.nextUnread, style: .plain, target: self, action: #selector(firstUnread(_:))) + + private lazy var dataSource = makeDataSource() + private let searchController = UISearchController(searchResultsController: nil) + + weak var coordinator: SceneCoordinator? + var undoableCommands = [UndoableCommand]() + let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0) + + private var timelineFeed: SidebarItem? { + assert(coordinator != nil) + return coordinator?.timelineFeed + } + + private var showIcons: Bool { + assert(coordinator != nil) + return coordinator?.showIcons ?? false + } + + private var currentArticle: Article? { + assert(coordinator != nil) + return coordinator?.currentArticle + } + + private var timelineMiddleIndexPath: IndexPath? { + get { + coordinator?.timelineMiddleIndexPath + } + set { + coordinator?.timelineMiddleIndexPath = newValue + } + } + + private var isTimelineViewControllerPending: Bool { + get { + coordinator?.isTimelineViewControllerPending ?? false + } + set { + coordinator?.isTimelineViewControllerPending = newValue + } + } + + private var timelineIconImage: IconImage? { + assert(coordinator != nil) + return coordinator?.timelineIconImage + } + + private var timelineDefaultReadFilterType: ReadFilterType { + return timelineFeed?.defaultReadFilterType ?? .none + } + + private var isReadArticlesFiltered: Bool { + assert(coordinator != nil) + return coordinator?.isReadArticlesFiltered ?? false + } + + private var isTimelineUnreadAvailable: Bool { + assert(coordinator != nil) + return coordinator?.isTimelineUnreadAvailable ?? false + } + + private var isRootSplitCollapsed: Bool { + assert(coordinator != nil) + return coordinator?.isRootSplitCollapsed ?? false + } + + private var articles: ArticleArray? { + assert(coordinator != nil) + return coordinator?.articles + } + + private let keyboardManager = KeyboardManager(type: .timeline) + override var keyCommands: [UIKeyCommand]? { + + // If the first responder is the WKWebView (PreloadedWebView) we don't want to supply any keyboard + // commands that the system is looking for by going up the responder chain. They will interfere with + // the WKWebViews built in hardware keyboard shortcuts, specifically the up and down arrow keys. + guard let current = UIResponder.currentFirstResponder, !(current is PreloadedWebView) else { return nil } + + return keyboardManager.keyCommands + } + + private lazy var navigationBarTitleLabel: UILabel = { + let label = UILabel() + label.font = UIFont.preferredFont(forTextStyle: .subheadline).bold() + label.isUserInteractionEnabled = true + label.numberOfLines = 1 + label.textAlignment = .center + label.adjustsFontForContentSizeCategory = false + let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) + label.addGestureRecognizer(tap) + let pointerInteraction = UIPointerInteraction(delegate: nil) + label.addInteraction(pointerInteraction) + return label + }() + + private lazy var navigationBarSubtitleTitleLabel: UILabel = { + let label = UILabel() + label.font = UIFont(name: "Helvetica", size: 12) + label.textColor = .systemGray + label.textAlignment = .center + label.isUserInteractionEnabled = true + label.adjustsFontForContentSizeCategory = false + let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) + label.addGestureRecognizer(tap) + return label + }() + + override var canBecomeFirstResponder: Bool { + true + } + + private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainTimelineViewController") + + override func viewDidLoad() { + Self.logger.debug("MainTimelineViewController: viewDidLoad") + + assert(coordinator != nil) + + super.viewDidLoad() + + 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(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in + self?.userDefaultsDidChange() + } + } + 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) + + // Setup the Search Controller + searchController.delegate = self + searchController.searchResultsUpdater = self + searchController.obscuresBackgroundDuringPresentation = false + searchController.searchBar.delegate = self + searchController.searchBar.placeholder = NSLocalizedString("Search Articles", comment: "Search Articles") + searchController.searchBar.scopeButtonTitles = [ + NSLocalizedString("Here", comment: "Here"), + NSLocalizedString("All Articles", comment: "All Articles") + ] + searchController.searchBar.barTintColor = .clear + searchController.searchBar.scopeBarBackgroundImage = UIImage() + searchController.searchBar.autocapitalizationType = .none + navigationItem.searchController = searchController + + if traitCollection.userInterfaceIdiom == .pad { + searchController.searchBar.selectedScopeButtonIndex = 1 + navigationItem.searchBarPlacementAllowsExternalIntegration = true + } + definesPresentationContext = true + + // Configure the table + tableView.dataSource = dataSource + tableView.isPrefetchingEnabled = false + + numberOfTextLines = AppDefaults.shared.timelineNumberOfLines + iconSize = AppDefaults.shared.timelineIconSize + + refreshControl = UIRefreshControl() + refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) + + configureToolbar() + resetUI(resetScroll: true) + + // Load the table and then scroll to the saved position if available + applyChanges(animated: false) { + if let restoreIndexPath = self.timelineMiddleIndexPath { + self.tableView.scrollToRow(at: restoreIndexPath, at: .middle, 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.titleView = navigationBarTitleLabel + navigationItem.subtitleView = navigationBarSubtitleTitleLabel + } + + 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 + } + + updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "") + coordinator?.updateNavigationBarSubtitles(nil) + } + + override func viewDidAppear(_ animated: Bool) { + Self.logger.debug("MainTimelineViewController: viewDidAppear") + + super.viewDidAppear(true) + isTimelineViewControllerPending = false + if navigationController?.navigationBar.alpha == 0 { + UIView.animate(withDuration: 0.5) { + self.navigationController?.navigationBar.alpha = 1 + } + } + if traitCollection.userInterfaceIdiom == .phone { + if coordinator?.currentArticle != nil { + if let indexPath = tableView.indexPathForSelectedRow { + tableView.deselectRow(at: indexPath, animated: true) + } + coordinator?.selectArticle(nil) + } + } + } + + // MARK: - Actions + + @objc func openInBrowser(_ sender: Any?) { + assert(coordinator != nil) + coordinator?.showBrowserForCurrentArticle() + } + + @objc func openInAppBrowser(_ sender: Any?) { + assert(coordinator != nil) + coordinator?.showInAppBrowser() + } + + @IBAction func toggleFilter(_ sender: Any) { + assert(coordinator != nil) + coordinator?.toggleReadArticlesFilter() + } + + private func markAllAsReadInTimeline() { + assert(coordinator != nil) + coordinator?.markAllAsReadInTimeline() + } + + @IBAction func markAllAsRead(_ sender: Any?) { + let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read") + + if let source = sender as? UIBarButtonItem { + MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: source) { [weak self] in + self?.markAllAsReadInTimeline() + } + } + + if sender is UIKeyCommand { + guard let indexPath = tableView.indexPathForSelectedRow, let contentView = tableView.cellForRow(at: indexPath)?.contentView else { + return + } + + MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in + self?.markAllAsReadInTimeline() + } + } + } + + @IBAction func firstUnread(_ sender: Any) { + assert(coordinator != nil) + coordinator?.selectFirstUnread() + } + + @objc func refreshAccounts(_ sender: Any) { + 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: - API + + func restoreSelectionIfNecessary(adjustScroll: Bool) { + if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { + if adjustScroll { + tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: []) + } else { + tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) + } + } + } + + func updateNavigationBarTitle(_ text: String) { + navigationItem.title = text + if let label = navigationItem.titleView as? UILabel { + label.text = text + label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) + label.sizeToFit() + } + } + + func updateNavigationBarSubtitle(_ text: String) { + if let label = navigationItem.subtitleView as? UILabel { + label.text = text + label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) + label.sizeToFit() + } + } + + func reinitializeArticles(resetScroll: Bool) { + Self.logger.debug("MainTimelineViewController: reinitializeArticles") + resetUI(resetScroll: resetScroll) + } + + func reloadArticles(animated: Bool) { + Self.logger.debug("MainTimelineViewController: reloadArticles") + applyChanges(animated: animated) + } + + func updateArticleSelection(animations: Animations) { + Self.logger.debug("MainTimelineViewController: updateArticleSelection") + + if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { + if tableView.indexPathForSelectedRow != indexPath { + tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: animations) + } + } else { + tableView.selectRow(at: nil, animated: animations.contains(.select), scrollPosition: .none) + } + + updateUI() + } + + func updateUI() { + Self.logger.debug("MainTimelineViewController: updateUI") + + refreshProgressView?.update() + updateToolbar() + } + + func hideSearch() { + navigationItem.searchController?.isActive = false + } + + func showSearchAll() { + navigationItem.searchController?.isActive = true + navigationItem.searchController?.searchBar.selectedScopeButtonIndex = 1 + navigationItem.searchController?.searchBar.becomeFirstResponder() + } + + func focus() { + Self.logger.debug("MainTimelineViewController: focus") + becomeFirstResponder() + } + + // MARK: - Table view + + override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { + guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } + guard !article.status.read || article.isAvailableToMarkUnread else { return nil } + + // Set up the read action + let readTitle = article.status.read ? + NSLocalizedString("Mark as Unread", comment: "Mark as Unread") : + NSLocalizedString("Mark as Read", comment: "Mark as Read") + + let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] _, _, completion in + self?.toggleRead(article) + completion(true) + } + + readAction.image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen + readAction.backgroundColor = Assets.Colors.primaryAccent + + return UISwipeActionsConfiguration(actions: [readAction]) + } + + override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { + + guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } + + // 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 + 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") + alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel) { _ in + completion(true) + }) + + self.present(alert, animated: true) + + } + + } + + moreAction.image = Assets.Images.more + moreAction.backgroundColor = UIColor.systemGray + + return UISwipeActionsConfiguration(actions: [starAction, moreAction]) + + } + + override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { + + guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } + + return UIContextMenuConfiguration(identifier: indexPath.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] _ in + + guard let self = self else { return nil } + + var menuElements = [UIMenuElement]() + + var markActions = [UIAction]() + if let action = self.toggleArticleReadStatusAction(article) { + markActions.append(action) + } + markActions.append(self.toggleArticleStarStatusAction(article)) + if let action = self.markAboveAsReadAction(article, indexPath: indexPath) { + markActions.append(action) + } + if let action = self.markBelowAsReadAction(article, indexPath: indexPath) { + 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: indexPath) { + 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: indexPath) { + menuElements.append(UIMenu(title: "", options: .displayInline, children: [action])) + } + + return UIMenu(title: "", children: menuElements) + + }) + + } + + override func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { + guard let row = configuration.identifier as? Int, + let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) else { + return nil + } + + let previewView = cell.contentView + let parameters = UIPreviewParameters() + parameters.backgroundColor = .white + parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, + cornerRadius: 20) + return UITargetedPreview(view: cell, parameters: parameters) + } + + override func tableView(_ tableView: UITableView, previewForDismissingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { + guard let row = configuration.identifier as? Int, + let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)), + view.window != nil else { + return nil + } + + let previewView = cell.contentView + let parameters = UIPreviewParameters() + parameters.backgroundColor = .white + parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, + cornerRadius: 20) + return UITargetedPreview(view: cell, parameters: parameters) + } + + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + becomeFirstResponder() + let article = dataSource.itemIdentifier(for: indexPath) + coordinator?.selectArticle(article, animations: [.scroll, .select, .navigation]) + } + + override func scrollViewDidScroll(_ scrollView: UIScrollView) { + scrollPositionQueue.add(self, #selector(scrollPositionDidChange)) + } + + // MARK: - Notifications + + @objc dynamic func unreadCountDidChange(_ notification: Notification) { + Self.logger.debug("MainTimelineViewController: unreadCountDidChange") + updateUI() + } + + @objc func statusesDidChange(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: statusesDidChange") + + guard isViewLoaded else { + return + } + guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set, !articleIDs.isEmpty else { + return + } + guard let indexPaths = tableView.indexPathsForVisibleRows else { + return + } + + let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } + let visibleUpdatedArticles = visibleArticles.filter { articleIDs.contains($0.articleID) } + + for article in visibleUpdatedArticles { + if let indexPath = dataSource.indexPath(for: article) { + if let cell = tableView.cellForRow(at: indexPath) as? MainTimelineCell { + let cellData = configure(article: article) + cell.cellData = cellData + } + } + } + } + + @objc func feedIconDidBecomeAvailable(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: feedIconDidBecomeAvailable") + + guard isViewLoaded else { + return + } + guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed else { + return + } + + updateIconForVisibleArticles(feed) + } + + @objc func avatarDidBecomeAvailable(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: avatarDidBecomeAvailable") + + guard isViewLoaded else { + return + } + guard showIcons, let avatarURL = note.userInfo?[UserInfoKey.url] as? String else { + return + } + guard let indexPaths = tableView.indexPathsForVisibleRows else { + return + } + + for indexPath in indexPaths { + guard let article = dataSource.itemIdentifier(for: indexPath), let authors = article.authors, !authors.isEmpty else { + continue + } + for author in authors { + if author.avatarURL == avatarURL, let cell = tableView.cellForRow(at: indexPath) as? MainTimelineCell, let image = iconImageFor(article) { + cell.setIconImage(image) + } + } + } + } + + @objc func faviconDidBecomeAvailable(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: faviconDidBecomeAvailable") + + guard isViewLoaded else { + return + } + + updateIconForVisibleArticles() + } + + /// Update icon for all visible articles — or, if feed is non-nil, update articles only from that feed. + private func updateIconForVisibleArticles(_ feed: Feed? = nil) { + guard isViewLoaded else { + return + } + guard showIcons else { + return + } + guard let indexPaths = tableView.indexPathsForVisibleRows else { + return + } + + for indexPath in indexPaths { + guard let article = dataSource.itemIdentifier(for: indexPath) else { + continue + } + if feed == nil || feed == article.feed { + if let cell = tableView.cellForRow(at: indexPath) as? MainTimelineCell, let image = iconImageFor(article) { + cell.setIconImage(image) + } + } + } + } + + func userDefaultsDidChange() { + Self.logger.debug("MainTimelineViewController: userDefaultsDidChange") + + if self.numberOfTextLines != AppDefaults.shared.timelineNumberOfLines || self.iconSize != AppDefaults.shared.timelineIconSize { + self.numberOfTextLines = AppDefaults.shared.timelineNumberOfLines + self.iconSize = AppDefaults.shared.timelineIconSize + self.reloadAllVisibleCells() + } + self.updateToolbar() + } + + @objc func contentSizeCategoryDidChange(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: contentSizeCategoryDidChange") + reloadAllVisibleCells() + } + + @objc func displayNameDidChange(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: displayNameDidChange") + updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "") + } + + @objc func willEnterForeground(_ note: Notification) { + Self.logger.debug("MainTimelineViewController: willEnterForeground") + updateUI() + } + + @objc func scrollPositionDidChange() { + Self.logger.debug("MainTimelineViewController: scrollPositionDidChange") + timelineMiddleIndexPath = tableView.middleVisibleRow() + } + + // MARK: - Reloading + + func queueReloadAvailableCells() { + CoalescingQueue.standard.add(self, #selector(reloadAllVisibleCells)) + } + + @objc private func reloadAllVisibleCells() { + guard isViewLoaded else { + return + } + guard let indexPaths = tableView.indexPathsForVisibleRows else { + return + } + + let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } + reloadCells(visibleArticles) + } + + private func reloadCells(_ articles: [Article]) { + guard !articles.isEmpty else { + return + } + + var snapshot = dataSource.snapshot() + snapshot.reloadItems(articles) + dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in + self?.restoreSelectionIfNecessary(adjustScroll: false) + } + } +} + +// MARK: Searching + +extension MainTimelineViewController: UISearchControllerDelegate { + + func willPresentSearchController(_ searchController: UISearchController) { + coordinator?.beginSearching() + searchController.searchBar.showsScopeBar = true + } + + func willDismissSearchController(_ searchController: UISearchController) { + coordinator?.endSearching() + searchController.searchBar.showsScopeBar = false + 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: Private + +private extension MainTimelineViewController { + + func searchArticles(_ searchString: String, _ searchScope: SearchScope) { + assert(coordinator != nil) + coordinator?.searchArticles(searchString, searchScope) + } + + func configureToolbar() { + if traitCollection.userInterfaceIdiom == .phone { + toolbarItems?.insert(.flexibleSpace(), at: 1) + toolbarItems?.insert(navigationItem.searchBarPlacementBarButtonItem, at: 2) + } + } + + func resetUI(resetScroll: Bool) { + let shouldShowFilterButton = coordinator?.shouldShowFilterButton() ?? false + navigationItem.rightBarButtonItem = shouldShowFilterButton ? filterButton : nil + + if isReadArticlesFiltered { + filterButton.style = .prominent + filterButton.tintColor = Assets.Colors.primaryAccent + filterButton.accLabelText = NSLocalizedString("Selected - Filter Read Articles", comment: "Selected - Filter Read Articles") + } else { + filterButton.style = .plain + filterButton.tintColor = nil + filterButton.accLabelText = NSLocalizedString("Filter Read Articles", comment: "Filter Read Articles") + } + + tableView.selectRow(at: nil, animated: false, scrollPosition: .top) + + if resetScroll { + let snapshot = dataSource.snapshot() + if snapshot.sectionIdentifiers.count > 0 && snapshot.itemIdentifiers(inSection: 0).count > 0 { + tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false) + } + } + + updateToolbar() + } + + func updateToolbar() { + markAllAsReadButton?.isEnabled = isTimelineUnreadAvailable + firstUnreadButton.isEnabled = coordinator?.isAnyUnreadAvailable ?? false + + if isRootSplitCollapsed { + if let toolbarItems = toolbarItems, toolbarItems.last != firstUnreadButton { + var items = toolbarItems + items.append(firstUnreadButton) + setToolbarItems(items, animated: false) + } + } else { + if let toolbarItems = toolbarItems, toolbarItems.last == firstUnreadButton { + let items = Array(toolbarItems[0.. Void)? = nil) { + if (articles?.count ?? 0) == 0 { + tableView.rowHeight = tableView.estimatedRowHeight + } else { + tableView.rowHeight = UITableView.automaticDimension + } + + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([0]) + snapshot.appendItems(articles ?? ArticleArray(), toSection: 0) + + dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in + self?.restoreSelectionIfNecessary(adjustScroll: false) + completion?() + } + } + + func makeDataSource() -> UITableViewDiffableDataSource { + let dataSource: UITableViewDiffableDataSource = + MainTimelineDataSource(tableView: tableView) { [weak self] tableView, indexPath, article in + guard let self else { + return nil + } + let cellData = self.configure(article: article) + let cellIdentifier: String = { + if self.showIcons { + return indexPath.row == 0 ? CellIdentifier.iconIndex0 : CellIdentifier.icon + } else { + return indexPath.row == 0 ? CellIdentifier.standardIndex0 : CellIdentifier.standard + } + }() + + // Force unwrapping because if this doesn't work then there are serious issues. + let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MainTimelineCell + cell.cellData = cellData + return cell + } + + dataSource.defaultRowAnimation = .middle + return dataSource + } + + @discardableResult + 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 + } + + func iconImageFor(_ article: Article) -> IconImage? { + if !showIcons { + return nil + } + return article.iconImage() + } + + 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: "Mark as Unread") : + NSLocalizedString("Mark as Read", comment: "Mark as Read") + let image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen + + let action = UIAction(title: title, image: image) { [weak self] _ in + 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: "Mark as Unstarred") : + NSLocalizedString("Mark as Starred", comment: "Mark as Starred") + let image = article.status.starred ? Assets.Images.starOpen : Assets.Images.starClosed + + let action = UIAction(title: title, image: image) { [weak self] _ in + 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 contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + return nil + } + + let title = NSLocalizedString("Mark Above as Read", comment: "Mark Above as Read") + 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? { + guard canMarkBelowAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + return nil + } + + let title = NSLocalizedString("Mark Below as Read", comment: "Mark Below as Read") + 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? { + guard canMarkAboveAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + return nil + } + + let title = NSLocalizedString("Mark Above as Read", comment: "Mark Above as Read") + 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? { + guard canMarkBelowAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + return nil + } + + let title = NSLocalizedString("Mark Below as Read", comment: "Mark Below as Read") + 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?.markAllAsRead(articles) + } + + func markAllInFeedAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? { + guard let feed = article.feed else { return nil } + guard let fetchedArticles = try? feed.fetchArticles() else { + return nil + } + + let articles = Array(fetchedArticles) + guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(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, 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 { return nil } + guard let fetchedArticles = try? feed.fetchArticles() else { + return nil + } + + let articles = Array(fetchedArticles) + guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + return nil + } + + let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Mark All as Read in Feed") + 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: "Copy Article URL") + 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: "Copy External URL") + 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: "Open in Browser") + 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: "Open in Browser") + 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 cell = tableView.cellForRow(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") + 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") + let action = UIAlertAction(title: title, style: .default) { [weak self] _ in + completion(true) + self?.shareDialogForTableCell(indexPath: indexPath, url: url, title: article.title) + } + return action + } + +} From 34666e104a076bf0161238ddc765bd3bf399adc1 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 14:40:55 +0800 Subject: [PATCH 09/15] Move CellIdentifier out of class It is needed for Customiser --- .../MainTimelineModernViewController.swift | 15 ++++++++------- .../TimelineCustomizerTableViewController.swift | 4 ++-- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/iOS/MainTimeline/MainTimelineModernViewController.swift b/iOS/MainTimeline/MainTimelineModernViewController.swift index 8482a0f59..372f3f1de 100644 --- a/iOS/MainTimeline/MainTimelineModernViewController.swift +++ b/iOS/MainTimeline/MainTimelineModernViewController.swift @@ -14,15 +14,16 @@ import RSWeb import Account import Articles + +struct CellIdentifier { + static let standard = "MainTimelineCellStandard" + static let standardIndex0 = "MainTimelineCellIndexZero" + static let icon = "MainTimelineCellIcon" + static let iconIndex0 = "MainTimelineCellIconIndexZero" +} + final class MainTimelineModernViewController: UIViewController, UndoableCommandRunner { - struct CellIdentifier { - static let standard = "MainTimelineCellStandard" - static let standardIndex0 = "MainTimelineCellIndexZero" - static let icon = "MainTimelineCellIcon" - static let iconIndex0 = "MainTimelineCellIconIndexZero" - } - // MARK: Private Variables private var numberOfTextLines = 0 private var iconSize = IconSize.medium diff --git a/iOS/Settings/TimelineCustomizerTableViewController.swift b/iOS/Settings/TimelineCustomizerTableViewController.swift index 46727b3e4..eeb0bbf86 100644 --- a/iOS/Settings/TimelineCustomizerTableViewController.swift +++ b/iOS/Settings/TimelineCustomizerTableViewController.swift @@ -88,7 +88,7 @@ final class TimelineCustomizerTableViewController: UITableViewController { } if indexPath.section == 2 { - let cell = tableView.dequeueReusableCell(withIdentifier: standardCellIdentifierIcon) as! MainTimelineCell + let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.icon) as! MainTimelineCell cell.cellData = MainTimelineCellData(article: previewArticle, showFeedName: .byline, feedName: "The Fellowship of the Ring", @@ -102,7 +102,7 @@ final class TimelineCustomizerTableViewController: UITableViewController { } if indexPath.section == 3 { - let cell = tableView.dequeueReusableCell(withIdentifier: standardCellIdentifier) as! MainTimelineCell + let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.standard) as! MainTimelineCell cell.cellData = MainTimelineCellData(article: previewArticle, showFeedName: .byline, feedName: "The Fellowship of the Ring", From c0df3f2de16d70235d74f3c51172ed7775580788 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 14:47:08 +0800 Subject: [PATCH 10/15] =?UTF-8?q?=F0=9F=A9=B9=20Fix=20#5014?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iOS/SceneCoordinator.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index 463bc93e4..acf0dc35f 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -2143,8 +2143,8 @@ private extension SceneCoordinator { // To be called when we need to do an entire fetch, but an async delay is okay. // Example: we have the Today feed selected, and the calendar day just changed. cancelPendingAsyncFetches() + emptyTheTimeline() guard let timelineFeed = timelineFeed else { - emptyTheTimeline() completion() return } From 4d21c0d26e0d87cee99c6f03de491eb7363e9ae7 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 14:49:34 +0800 Subject: [PATCH 11/15] =?UTF-8?q?=F0=9F=91=BD=EF=B8=8F=20Consistency=20wit?= =?UTF-8?q?h=20main?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MainTimelineModernViewController.swift | 14 +++++++------- .../TimelineCustomizerTableViewController.swift | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/iOS/MainTimeline/MainTimelineModernViewController.swift b/iOS/MainTimeline/MainTimelineModernViewController.swift index 372f3f1de..c84682ad5 100644 --- a/iOS/MainTimeline/MainTimelineModernViewController.swift +++ b/iOS/MainTimeline/MainTimelineModernViewController.swift @@ -15,15 +15,15 @@ import Account import Articles -struct CellIdentifier { - static let standard = "MainTimelineCellStandard" - static let standardIndex0 = "MainTimelineCellIndexZero" - static let icon = "MainTimelineCellIcon" - static let iconIndex0 = "MainTimelineCellIconIndexZero" -} - final class MainTimelineModernViewController: UIViewController, UndoableCommandRunner { + struct CellIdentifier { + static let standard = "MainTimelineCellStandard" + static let standardIndex0 = "MainTimelineCellIndexZero" + static let icon = "MainTimelineCellIcon" + static let iconIndex0 = "MainTimelineCellIconIndexZero" + } + // MARK: Private Variables private var numberOfTextLines = 0 private var iconSize = IconSize.medium diff --git a/iOS/Settings/TimelineCustomizerTableViewController.swift b/iOS/Settings/TimelineCustomizerTableViewController.swift index eeb0bbf86..1bcb2dba2 100644 --- a/iOS/Settings/TimelineCustomizerTableViewController.swift +++ b/iOS/Settings/TimelineCustomizerTableViewController.swift @@ -88,7 +88,7 @@ final class TimelineCustomizerTableViewController: UITableViewController { } if indexPath.section == 2 { - let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.icon) as! MainTimelineCell + let cell = tableView.dequeueReusableCell(withIdentifier: MainTimelineModernViewController.CellIdentifier.icon) as! MainTimelineCell cell.cellData = MainTimelineCellData(article: previewArticle, showFeedName: .byline, feedName: "The Fellowship of the Ring", @@ -102,7 +102,7 @@ final class TimelineCustomizerTableViewController: UITableViewController { } if indexPath.section == 3 { - let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.standard) as! MainTimelineCell + let cell = tableView.dequeueReusableCell(withIdentifier: MainTimelineModernViewController.CellIdentifier.standard) as! MainTimelineCell cell.cellData = MainTimelineCellData(article: previewArticle, showFeedName: .byline, feedName: "The Fellowship of the Ring", From 3b5db807aeea220b6155679c4d6ecc3c038bd56c Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 17:29:26 +0800 Subject: [PATCH 12/15] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Cells=20go=20under?= =?UTF-8?q?=20sidebar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit leading swipe action misbehaves on ipad when sidebar is displayed --- iOS/Base.lproj/Main.storyboard | 78 ++++++++++--------- .../MainTimelineModernViewController.swift | 38 ++++----- 2 files changed, 61 insertions(+), 55 deletions(-) diff --git a/iOS/Base.lproj/Main.storyboard b/iOS/Base.lproj/Main.storyboard index 023e3824e..773ed6d0c 100644 --- a/iOS/Base.lproj/Main.storyboard +++ b/iOS/Base.lproj/Main.storyboard @@ -474,10 +474,10 @@ - + - + @@ -487,7 +487,7 @@ - + @@ -530,19 +530,20 @@ + - + - - - + + + - - + + - + @@ -558,7 +559,7 @@ - + @@ -601,18 +602,19 @@ + - + - + - + - - - + + + - + @@ -629,7 +631,7 @@ - + @@ -679,22 +681,23 @@ + - - - + + + - + - + - + - + - + @@ -711,7 +714,7 @@ - + @@ -761,21 +764,22 @@ + - - - + + + - + - + - + - + - + @@ -802,7 +806,7 @@ - + diff --git a/iOS/MainTimeline/MainTimelineModernViewController.swift b/iOS/MainTimeline/MainTimelineModernViewController.swift index c84682ad5..b8b5ebc80 100644 --- a/iOS/MainTimeline/MainTimelineModernViewController.swift +++ b/iOS/MainTimeline/MainTimelineModernViewController.swift @@ -145,7 +145,6 @@ final class MainTimelineModernViewController: UIViewController, UndoableCommandR // MARK: Constants let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0) - // MARK: - IBOutlets @IBOutlet var markAllAsReadButton: UIBarButtonItem? @IBOutlet var collectionView: UICollectionView! @@ -153,6 +152,7 @@ final class MainTimelineModernViewController: UIViewController, UndoableCommandR override func viewDidLoad() { super.viewDidLoad() + addNotificationObservers() configureCollectionView() configureSearchController() @@ -187,7 +187,7 @@ final class MainTimelineModernViewController: UIViewController, UndoableCommandR navigationItem.subtitleView = navigationBarSubtitleTitleLabel // Do any additional setup after loading the view. } - + override func viewWillAppear(_ animated: Bool) { Self.logger.debug("MainTimelineModernViewController: viewWillAppear") @@ -446,13 +446,13 @@ extension MainTimelineModernViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemsAt indexPaths: [IndexPath], point: CGPoint) -> UIContextMenuConfiguration? { guard let firstIndex = indexPaths.first, let article = dataSource.itemIdentifier(for: firstIndex) else { return nil } - + return UIContextMenuConfiguration(identifier: firstIndex.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] _ in - + guard let self = self else { return nil } - + var menuElements = [UIMenuElement]() - + var markActions = [UIAction]() if let action = self.toggleArticleReadStatusAction(article) { markActions.append(action) @@ -465,7 +465,7 @@ extension MainTimelineModernViewController: UICollectionViewDelegate { markActions.append(action) } menuElements.append(UIMenu(title: "", options: .displayInline, children: markActions)) - + var secondaryActions = [UIAction]() if let action = self.discloseFeedAction(article) { secondaryActions.append(action) @@ -476,7 +476,7 @@ extension MainTimelineModernViewController: UICollectionViewDelegate { if !secondaryActions.isEmpty { menuElements.append(UIMenu(title: "", options: .displayInline, children: secondaryActions)) } - + var copyActions = [UIAction]() if let action = self.copyArticleURLAction(article) { copyActions.append(action) @@ -487,26 +487,26 @@ extension MainTimelineModernViewController: UICollectionViewDelegate { if !copyActions.isEmpty { menuElements.append(UIMenu(title: "", options: .displayInline, children: copyActions)) } - + if let action = self.openInBrowserAction(article) { menuElements.append(UIMenu(title: "", options: .displayInline, children: [action])) } - + if let action = self.shareAction(article, indexPath: firstIndex) { menuElements.append(UIMenu(title: "", options: .displayInline, children: [action])) } - + return UIMenu(title: "", children: menuElements) - + }) } func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, highlightPreviewForItemAt indexPath: IndexPath) -> UITargetedPreview? { guard let row = configuration.identifier as? Int, - let cell = collectionView.cellForItem(at: IndexPath(row: row, section: 0)) else { - return nil + let cell = collectionView.cellForItem(at: IndexPath(row: row, section: 0)) else { + return nil } - + let previewView = cell.contentView let parameters = UIPreviewParameters() parameters.backgroundColor = .white @@ -519,9 +519,9 @@ extension MainTimelineModernViewController: UICollectionViewDelegate { 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)), let _ = view.window else { - return nil + return nil } - + let previewView = cell.contentView let parameters = UIPreviewParameters() parameters.backgroundColor = .white @@ -529,6 +529,8 @@ extension MainTimelineModernViewController: UICollectionViewDelegate { cornerRadius: 20) return UITargetedPreview(view: cell, parameters: parameters) } + + } // MARK: Private API @@ -697,7 +699,7 @@ private extension MainTimelineModernViewController { collectionView.refreshControl = UIRefreshControl() collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) - collectionView.contentInsetAdjustmentBehavior = .always + collectionView.contentInsetAdjustmentBehavior = .automatic let layout = UICollectionViewCompositionalLayout.list(using: config) layout.configuration.contentInsetsReference = .safeArea From 1f608ae2628223d0cce4c86084e687ead6335da2 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 18:42:50 +0800 Subject: [PATCH 13/15] =?UTF-8?q?=F0=9F=94=A5=20Delete=20old=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MainTimelineViewController.swift | 1232 ----------------- 1 file changed, 1232 deletions(-) delete mode 100644 iOS/MainTimeline/MainTimelineViewController.swift diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift deleted file mode 100644 index aa780bd20..000000000 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ /dev/null @@ -1,1232 +0,0 @@ -// -// MainTimelineViewController.swift -// NetNewsWire -// -// Created by Stuart Breckenridge on 25/01/2026. -// Copyright © 2026 Ranchero Software. All rights reserved. -// - - -// -// MainTimelineViewController.swift -// NetNewsWire -// -// Created by Maurice Parker on 4/8/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit -import os -import WebKit -import RSCore -import RSWeb -import Account -import Articles - -final class MainTimelineViewController: UITableViewController, UndoableCommandRunner { - struct CellIdentifier { - static let standard = "MainTimelineCellStandard" - static let standardIndex0 = "MainTimelineCellIndexZero" - static let icon = "MainTimelineCellIcon" - static let iconIndex0 = "MainTimelineCellIconIndexZero" - } - - private var numberOfTextLines = 0 - private var iconSize = IconSize.medium - private lazy var feedTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) - - private var refreshProgressView: RefreshProgressView? - - @IBOutlet var markAllAsReadButton: UIBarButtonItem? - - private lazy var filterButton = UIBarButtonItem(image: Assets.Images.filter, style: .plain, target: self, action: #selector(toggleFilter(_:))) - private lazy var firstUnreadButton = UIBarButtonItem(image: Assets.Images.nextUnread, style: .plain, target: self, action: #selector(firstUnread(_:))) - - private lazy var dataSource = makeDataSource() - private let searchController = UISearchController(searchResultsController: nil) - - weak var coordinator: SceneCoordinator? - var undoableCommands = [UndoableCommand]() - let scrollPositionQueue = CoalescingQueue(name: "Timeline Scroll Position", interval: 0.3, maxInterval: 1.0) - - private var timelineFeed: SidebarItem? { - assert(coordinator != nil) - return coordinator?.timelineFeed - } - - private var showIcons: Bool { - assert(coordinator != nil) - return coordinator?.showIcons ?? false - } - - private var currentArticle: Article? { - assert(coordinator != nil) - return coordinator?.currentArticle - } - - private var timelineMiddleIndexPath: IndexPath? { - get { - coordinator?.timelineMiddleIndexPath - } - set { - coordinator?.timelineMiddleIndexPath = newValue - } - } - - private var isTimelineViewControllerPending: Bool { - get { - coordinator?.isTimelineViewControllerPending ?? false - } - set { - coordinator?.isTimelineViewControllerPending = newValue - } - } - - private var timelineIconImage: IconImage? { - assert(coordinator != nil) - return coordinator?.timelineIconImage - } - - private var timelineDefaultReadFilterType: ReadFilterType { - return timelineFeed?.defaultReadFilterType ?? .none - } - - private var isReadArticlesFiltered: Bool { - assert(coordinator != nil) - return coordinator?.isReadArticlesFiltered ?? false - } - - private var isTimelineUnreadAvailable: Bool { - assert(coordinator != nil) - return coordinator?.isTimelineUnreadAvailable ?? false - } - - private var isRootSplitCollapsed: Bool { - assert(coordinator != nil) - return coordinator?.isRootSplitCollapsed ?? false - } - - private var articles: ArticleArray? { - assert(coordinator != nil) - return coordinator?.articles - } - - private let keyboardManager = KeyboardManager(type: .timeline) - override var keyCommands: [UIKeyCommand]? { - - // If the first responder is the WKWebView (PreloadedWebView) we don't want to supply any keyboard - // commands that the system is looking for by going up the responder chain. They will interfere with - // the WKWebViews built in hardware keyboard shortcuts, specifically the up and down arrow keys. - guard let current = UIResponder.currentFirstResponder, !(current is PreloadedWebView) else { return nil } - - return keyboardManager.keyCommands - } - - private lazy var navigationBarTitleLabel: UILabel = { - let label = UILabel() - label.font = UIFont.preferredFont(forTextStyle: .subheadline).bold() - label.isUserInteractionEnabled = true - label.numberOfLines = 1 - label.textAlignment = .center - label.adjustsFontForContentSizeCategory = false - let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) - label.addGestureRecognizer(tap) - let pointerInteraction = UIPointerInteraction(delegate: nil) - label.addInteraction(pointerInteraction) - return label - }() - - private lazy var navigationBarSubtitleTitleLabel: UILabel = { - let label = UILabel() - label.font = UIFont(name: "Helvetica", size: 12) - label.textColor = .systemGray - label.textAlignment = .center - label.isUserInteractionEnabled = true - label.adjustsFontForContentSizeCategory = false - let tap = UITapGestureRecognizer(target: self, action: #selector(showFeedInspector(_:))) - label.addGestureRecognizer(tap) - return label - }() - - override var canBecomeFirstResponder: Bool { - true - } - - private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "MainTimelineViewController") - - override func viewDidLoad() { - Self.logger.debug("MainTimelineViewController: viewDidLoad") - - assert(coordinator != nil) - - super.viewDidLoad() - - 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(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in - Task { @MainActor in - self?.userDefaultsDidChange() - } - } - 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) - - // Setup the Search Controller - searchController.delegate = self - searchController.searchResultsUpdater = self - searchController.obscuresBackgroundDuringPresentation = false - searchController.searchBar.delegate = self - searchController.searchBar.placeholder = NSLocalizedString("Search Articles", comment: "Search Articles") - searchController.searchBar.scopeButtonTitles = [ - NSLocalizedString("Here", comment: "Here"), - NSLocalizedString("All Articles", comment: "All Articles") - ] - searchController.searchBar.barTintColor = .clear - searchController.searchBar.scopeBarBackgroundImage = UIImage() - searchController.searchBar.autocapitalizationType = .none - navigationItem.searchController = searchController - - if traitCollection.userInterfaceIdiom == .pad { - searchController.searchBar.selectedScopeButtonIndex = 1 - navigationItem.searchBarPlacementAllowsExternalIntegration = true - } - definesPresentationContext = true - - // Configure the table - tableView.dataSource = dataSource - tableView.isPrefetchingEnabled = false - - numberOfTextLines = AppDefaults.shared.timelineNumberOfLines - iconSize = AppDefaults.shared.timelineIconSize - - refreshControl = UIRefreshControl() - refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) - - configureToolbar() - resetUI(resetScroll: true) - - // Load the table and then scroll to the saved position if available - applyChanges(animated: false) { - if let restoreIndexPath = self.timelineMiddleIndexPath { - self.tableView.scrollToRow(at: restoreIndexPath, at: .middle, 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.titleView = navigationBarTitleLabel - navigationItem.subtitleView = navigationBarSubtitleTitleLabel - } - - 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 - } - - updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "") - coordinator?.updateNavigationBarSubtitles(nil) - } - - override func viewDidAppear(_ animated: Bool) { - Self.logger.debug("MainTimelineViewController: viewDidAppear") - - super.viewDidAppear(true) - isTimelineViewControllerPending = false - if navigationController?.navigationBar.alpha == 0 { - UIView.animate(withDuration: 0.5) { - self.navigationController?.navigationBar.alpha = 1 - } - } - if traitCollection.userInterfaceIdiom == .phone { - if coordinator?.currentArticle != nil { - if let indexPath = tableView.indexPathForSelectedRow { - tableView.deselectRow(at: indexPath, animated: true) - } - coordinator?.selectArticle(nil) - } - } - } - - // MARK: - Actions - - @objc func openInBrowser(_ sender: Any?) { - assert(coordinator != nil) - coordinator?.showBrowserForCurrentArticle() - } - - @objc func openInAppBrowser(_ sender: Any?) { - assert(coordinator != nil) - coordinator?.showInAppBrowser() - } - - @IBAction func toggleFilter(_ sender: Any) { - assert(coordinator != nil) - coordinator?.toggleReadArticlesFilter() - } - - private func markAllAsReadInTimeline() { - assert(coordinator != nil) - coordinator?.markAllAsReadInTimeline() - } - - @IBAction func markAllAsRead(_ sender: Any?) { - let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read") - - if let source = sender as? UIBarButtonItem { - MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: source) { [weak self] in - self?.markAllAsReadInTimeline() - } - } - - if sender is UIKeyCommand { - guard let indexPath = tableView.indexPathForSelectedRow, let contentView = tableView.cellForRow(at: indexPath)?.contentView else { - return - } - - MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in - self?.markAllAsReadInTimeline() - } - } - } - - @IBAction func firstUnread(_ sender: Any) { - assert(coordinator != nil) - coordinator?.selectFirstUnread() - } - - @objc func refreshAccounts(_ sender: Any) { - 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: - API - - func restoreSelectionIfNecessary(adjustScroll: Bool) { - if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { - if adjustScroll { - tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: []) - } else { - tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) - } - } - } - - func updateNavigationBarTitle(_ text: String) { - navigationItem.title = text - if let label = navigationItem.titleView as? UILabel { - label.text = text - label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) - label.sizeToFit() - } - } - - func updateNavigationBarSubtitle(_ text: String) { - if let label = navigationItem.subtitleView as? UILabel { - label.text = text - label.isUserInteractionEnabled = ((coordinator?.timelineFeed as? PseudoFeed) == nil) - label.sizeToFit() - } - } - - func reinitializeArticles(resetScroll: Bool) { - Self.logger.debug("MainTimelineViewController: reinitializeArticles") - resetUI(resetScroll: resetScroll) - } - - func reloadArticles(animated: Bool) { - Self.logger.debug("MainTimelineViewController: reloadArticles") - applyChanges(animated: animated) - } - - func updateArticleSelection(animations: Animations) { - Self.logger.debug("MainTimelineViewController: updateArticleSelection") - - if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) { - if tableView.indexPathForSelectedRow != indexPath { - tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: animations) - } - } else { - tableView.selectRow(at: nil, animated: animations.contains(.select), scrollPosition: .none) - } - - updateUI() - } - - func updateUI() { - Self.logger.debug("MainTimelineViewController: updateUI") - - refreshProgressView?.update() - updateToolbar() - } - - func hideSearch() { - navigationItem.searchController?.isActive = false - } - - func showSearchAll() { - navigationItem.searchController?.isActive = true - navigationItem.searchController?.searchBar.selectedScopeButtonIndex = 1 - navigationItem.searchController?.searchBar.becomeFirstResponder() - } - - func focus() { - Self.logger.debug("MainTimelineViewController: focus") - becomeFirstResponder() - } - - // MARK: - Table view - - override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { - guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - guard !article.status.read || article.isAvailableToMarkUnread else { return nil } - - // Set up the read action - let readTitle = article.status.read ? - NSLocalizedString("Mark as Unread", comment: "Mark as Unread") : - NSLocalizedString("Mark as Read", comment: "Mark as Read") - - let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] _, _, completion in - self?.toggleRead(article) - completion(true) - } - - readAction.image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen - readAction.backgroundColor = Assets.Colors.primaryAccent - - return UISwipeActionsConfiguration(actions: [readAction]) - } - - override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { - - guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - - // 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 - 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") - alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel) { _ in - completion(true) - }) - - self.present(alert, animated: true) - - } - - } - - moreAction.image = Assets.Images.more - moreAction.backgroundColor = UIColor.systemGray - - return UISwipeActionsConfiguration(actions: [starAction, moreAction]) - - } - - override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { - - guard let article = dataSource.itemIdentifier(for: indexPath) else { return nil } - - return UIContextMenuConfiguration(identifier: indexPath.row as NSCopying, previewProvider: nil, actionProvider: { [weak self] _ in - - guard let self = self else { return nil } - - var menuElements = [UIMenuElement]() - - var markActions = [UIAction]() - if let action = self.toggleArticleReadStatusAction(article) { - markActions.append(action) - } - markActions.append(self.toggleArticleStarStatusAction(article)) - if let action = self.markAboveAsReadAction(article, indexPath: indexPath) { - markActions.append(action) - } - if let action = self.markBelowAsReadAction(article, indexPath: indexPath) { - 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: indexPath) { - 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: indexPath) { - menuElements.append(UIMenu(title: "", options: .displayInline, children: [action])) - } - - return UIMenu(title: "", children: menuElements) - - }) - - } - - override func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { - guard let row = configuration.identifier as? Int, - let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) else { - return nil - } - - let previewView = cell.contentView - let parameters = UIPreviewParameters() - parameters.backgroundColor = .white - parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, - cornerRadius: 20) - return UITargetedPreview(view: cell, parameters: parameters) - } - - override func tableView(_ tableView: UITableView, previewForDismissingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { - guard let row = configuration.identifier as? Int, - let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)), - view.window != nil else { - return nil - } - - let previewView = cell.contentView - let parameters = UIPreviewParameters() - parameters.backgroundColor = .white - parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, - cornerRadius: 20) - return UITargetedPreview(view: cell, parameters: parameters) - } - - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - becomeFirstResponder() - let article = dataSource.itemIdentifier(for: indexPath) - coordinator?.selectArticle(article, animations: [.scroll, .select, .navigation]) - } - - override func scrollViewDidScroll(_ scrollView: UIScrollView) { - scrollPositionQueue.add(self, #selector(scrollPositionDidChange)) - } - - // MARK: - Notifications - - @objc dynamic func unreadCountDidChange(_ notification: Notification) { - Self.logger.debug("MainTimelineViewController: unreadCountDidChange") - updateUI() - } - - @objc func statusesDidChange(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: statusesDidChange") - - guard isViewLoaded else { - return - } - guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set, !articleIDs.isEmpty else { - return - } - guard let indexPaths = tableView.indexPathsForVisibleRows else { - return - } - - let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } - let visibleUpdatedArticles = visibleArticles.filter { articleIDs.contains($0.articleID) } - - for article in visibleUpdatedArticles { - if let indexPath = dataSource.indexPath(for: article) { - if let cell = tableView.cellForRow(at: indexPath) as? MainTimelineCell { - let cellData = configure(article: article) - cell.cellData = cellData - } - } - } - } - - @objc func feedIconDidBecomeAvailable(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: feedIconDidBecomeAvailable") - - guard isViewLoaded else { - return - } - guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed else { - return - } - - updateIconForVisibleArticles(feed) - } - - @objc func avatarDidBecomeAvailable(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: avatarDidBecomeAvailable") - - guard isViewLoaded else { - return - } - guard showIcons, let avatarURL = note.userInfo?[UserInfoKey.url] as? String else { - return - } - guard let indexPaths = tableView.indexPathsForVisibleRows else { - return - } - - for indexPath in indexPaths { - guard let article = dataSource.itemIdentifier(for: indexPath), let authors = article.authors, !authors.isEmpty else { - continue - } - for author in authors { - if author.avatarURL == avatarURL, let cell = tableView.cellForRow(at: indexPath) as? MainTimelineCell, let image = iconImageFor(article) { - cell.setIconImage(image) - } - } - } - } - - @objc func faviconDidBecomeAvailable(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: faviconDidBecomeAvailable") - - guard isViewLoaded else { - return - } - - updateIconForVisibleArticles() - } - - /// Update icon for all visible articles — or, if feed is non-nil, update articles only from that feed. - private func updateIconForVisibleArticles(_ feed: Feed? = nil) { - guard isViewLoaded else { - return - } - guard showIcons else { - return - } - guard let indexPaths = tableView.indexPathsForVisibleRows else { - return - } - - for indexPath in indexPaths { - guard let article = dataSource.itemIdentifier(for: indexPath) else { - continue - } - if feed == nil || feed == article.feed { - if let cell = tableView.cellForRow(at: indexPath) as? MainTimelineCell, let image = iconImageFor(article) { - cell.setIconImage(image) - } - } - } - } - - func userDefaultsDidChange() { - Self.logger.debug("MainTimelineViewController: userDefaultsDidChange") - - if self.numberOfTextLines != AppDefaults.shared.timelineNumberOfLines || self.iconSize != AppDefaults.shared.timelineIconSize { - self.numberOfTextLines = AppDefaults.shared.timelineNumberOfLines - self.iconSize = AppDefaults.shared.timelineIconSize - self.reloadAllVisibleCells() - } - self.updateToolbar() - } - - @objc func contentSizeCategoryDidChange(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: contentSizeCategoryDidChange") - reloadAllVisibleCells() - } - - @objc func displayNameDidChange(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: displayNameDidChange") - updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "") - } - - @objc func willEnterForeground(_ note: Notification) { - Self.logger.debug("MainTimelineViewController: willEnterForeground") - updateUI() - } - - @objc func scrollPositionDidChange() { - Self.logger.debug("MainTimelineViewController: scrollPositionDidChange") - timelineMiddleIndexPath = tableView.middleVisibleRow() - } - - // MARK: - Reloading - - func queueReloadAvailableCells() { - CoalescingQueue.standard.add(self, #selector(reloadAllVisibleCells)) - } - - @objc private func reloadAllVisibleCells() { - guard isViewLoaded else { - return - } - guard let indexPaths = tableView.indexPathsForVisibleRows else { - return - } - - let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } - reloadCells(visibleArticles) - } - - private func reloadCells(_ articles: [Article]) { - guard !articles.isEmpty else { - return - } - - var snapshot = dataSource.snapshot() - snapshot.reloadItems(articles) - dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in - self?.restoreSelectionIfNecessary(adjustScroll: false) - } - } -} - -// MARK: Searching - -extension MainTimelineViewController: UISearchControllerDelegate { - - func willPresentSearchController(_ searchController: UISearchController) { - coordinator?.beginSearching() - searchController.searchBar.showsScopeBar = true - } - - func willDismissSearchController(_ searchController: UISearchController) { - coordinator?.endSearching() - searchController.searchBar.showsScopeBar = false - 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: Private - -private extension MainTimelineViewController { - - func searchArticles(_ searchString: String, _ searchScope: SearchScope) { - assert(coordinator != nil) - coordinator?.searchArticles(searchString, searchScope) - } - - func configureToolbar() { - if traitCollection.userInterfaceIdiom == .phone { - toolbarItems?.insert(.flexibleSpace(), at: 1) - toolbarItems?.insert(navigationItem.searchBarPlacementBarButtonItem, at: 2) - } - } - - func resetUI(resetScroll: Bool) { - let shouldShowFilterButton = coordinator?.shouldShowFilterButton() ?? false - navigationItem.rightBarButtonItem = shouldShowFilterButton ? filterButton : nil - - if isReadArticlesFiltered { - filterButton.style = .prominent - filterButton.tintColor = Assets.Colors.primaryAccent - filterButton.accLabelText = NSLocalizedString("Selected - Filter Read Articles", comment: "Selected - Filter Read Articles") - } else { - filterButton.style = .plain - filterButton.tintColor = nil - filterButton.accLabelText = NSLocalizedString("Filter Read Articles", comment: "Filter Read Articles") - } - - tableView.selectRow(at: nil, animated: false, scrollPosition: .top) - - if resetScroll { - let snapshot = dataSource.snapshot() - if snapshot.sectionIdentifiers.count > 0 && snapshot.itemIdentifiers(inSection: 0).count > 0 { - tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false) - } - } - - updateToolbar() - } - - func updateToolbar() { - markAllAsReadButton?.isEnabled = isTimelineUnreadAvailable - firstUnreadButton.isEnabled = coordinator?.isAnyUnreadAvailable ?? false - - if isRootSplitCollapsed { - if let toolbarItems = toolbarItems, toolbarItems.last != firstUnreadButton { - var items = toolbarItems - items.append(firstUnreadButton) - setToolbarItems(items, animated: false) - } - } else { - if let toolbarItems = toolbarItems, toolbarItems.last == firstUnreadButton { - let items = Array(toolbarItems[0.. Void)? = nil) { - if (articles?.count ?? 0) == 0 { - tableView.rowHeight = tableView.estimatedRowHeight - } else { - tableView.rowHeight = UITableView.automaticDimension - } - - var snapshot = NSDiffableDataSourceSnapshot() - snapshot.appendSections([0]) - snapshot.appendItems(articles ?? ArticleArray(), toSection: 0) - - dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in - self?.restoreSelectionIfNecessary(adjustScroll: false) - completion?() - } - } - - func makeDataSource() -> UITableViewDiffableDataSource { - let dataSource: UITableViewDiffableDataSource = - MainTimelineDataSource(tableView: tableView) { [weak self] tableView, indexPath, article in - guard let self else { - return nil - } - let cellData = self.configure(article: article) - let cellIdentifier: String = { - if self.showIcons { - return indexPath.row == 0 ? CellIdentifier.iconIndex0 : CellIdentifier.icon - } else { - return indexPath.row == 0 ? CellIdentifier.standardIndex0 : CellIdentifier.standard - } - }() - - // Force unwrapping because if this doesn't work then there are serious issues. - let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MainTimelineCell - cell.cellData = cellData - return cell - } - - dataSource.defaultRowAnimation = .middle - return dataSource - } - - @discardableResult - 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 - } - - func iconImageFor(_ article: Article) -> IconImage? { - if !showIcons { - return nil - } - return article.iconImage() - } - - 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: "Mark as Unread") : - NSLocalizedString("Mark as Read", comment: "Mark as Read") - let image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen - - let action = UIAction(title: title, image: image) { [weak self] _ in - 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: "Mark as Unstarred") : - NSLocalizedString("Mark as Starred", comment: "Mark as Starred") - let image = article.status.starred ? Assets.Images.starOpen : Assets.Images.starClosed - - let action = UIAction(title: title, image: image) { [weak self] _ in - 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 contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let title = NSLocalizedString("Mark Above as Read", comment: "Mark Above as Read") - 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? { - guard canMarkBelowAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let title = NSLocalizedString("Mark Below as Read", comment: "Mark Below as Read") - 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? { - guard canMarkAboveAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let title = NSLocalizedString("Mark Above as Read", comment: "Mark Above as Read") - 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? { - guard canMarkBelowAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let title = NSLocalizedString("Mark Below as Read", comment: "Mark Below as Read") - 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?.markAllAsRead(articles) - } - - func markAllInFeedAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? { - guard let feed = article.feed else { return nil } - guard let fetchedArticles = try? feed.fetchArticles() else { - return nil - } - - let articles = Array(fetchedArticles) - guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(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, 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 { return nil } - guard let fetchedArticles = try? feed.fetchArticles() else { - return nil - } - - let articles = Array(fetchedArticles) - guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { - return nil - } - - let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Mark All as Read in Feed") - 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: "Copy Article URL") - 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: "Copy External URL") - 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: "Open in Browser") - 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: "Open in Browser") - 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 cell = tableView.cellForRow(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") - 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") - let action = UIAlertAction(title: title, style: .default) { [weak self] _ in - completion(true) - self?.shareDialogForTableCell(indexPath: indexPath, url: url, title: article.title) - } - return action - } - -} From bd1d159fc2e157dbb14033ecf52fb79a0013172e Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 18:45:44 +0800 Subject: [PATCH 14/15] =?UTF-8?q?=F0=9F=94=A5=20Remove=20old=20timeline=20?= =?UTF-8?q?from=20Storyboard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iOS/Base.lproj/Main.storyboard | 355 --------------------------------- 1 file changed, 355 deletions(-) diff --git a/iOS/Base.lproj/Main.storyboard b/iOS/Base.lproj/Main.storyboard index 773ed6d0c..a260dda91 100644 --- a/iOS/Base.lproj/Main.storyboard +++ b/iOS/Base.lproj/Main.storyboard @@ -7,7 +7,6 @@ - @@ -113,360 +112,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From df8dce742a41139a06a9bdbc303597d840efe5f3 Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Sun, 25 Jan 2026 18:53:24 +0800 Subject: [PATCH 15/15] =?UTF-8?q?=F0=9F=92=84=20Dark=20mode=20support=20fo?= =?UTF-8?q?r=20context=20menu=20previews?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iOS/MainTimeline/MainTimelineModernViewController.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/iOS/MainTimeline/MainTimelineModernViewController.swift b/iOS/MainTimeline/MainTimelineModernViewController.swift index b8b5ebc80..d4842b59f 100644 --- a/iOS/MainTimeline/MainTimelineModernViewController.swift +++ b/iOS/MainTimeline/MainTimelineModernViewController.swift @@ -509,7 +509,7 @@ extension MainTimelineModernViewController: UICollectionViewDelegate { let previewView = cell.contentView let parameters = UIPreviewParameters() - parameters.backgroundColor = .white + parameters.backgroundColor = .tertiarySystemBackground parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, cornerRadius: 20) return UITargetedPreview(view: cell, parameters: parameters) @@ -524,7 +524,7 @@ extension MainTimelineModernViewController: UICollectionViewDelegate { let previewView = cell.contentView let parameters = UIPreviewParameters() - parameters.backgroundColor = .white + parameters.backgroundColor = .clear parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, cornerRadius: 20) return UITargetedPreview(view: cell, parameters: parameters)