diff --git a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift index e3ab8d830..ef25e5968 100644 --- a/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift +++ b/Modules/RSCore/Sources/RSCore/UIKit/UICollectionView+RSCore.swift @@ -22,12 +22,19 @@ 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) } } + + public func middleVisibleRow() -> IndexPath? { + if indexPathsForVisibleItems.count > 2 { + return indexPathsForVisibleItems[indexPathsForVisibleItems.count / 2] + } + return nil + } } diff --git a/iOS/Base.lproj/Main.storyboard b/iOS/Base.lproj/Main.storyboard index a1e944b44..a260dda91 100644 --- a/iOS/Base.lproj/Main.storyboard +++ b/iOS/Base.lproj/Main.storyboard @@ -7,7 +7,6 @@ - @@ -113,367 +112,379 @@ - + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - + - + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - + - + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + + + + + + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + - - - - - - - + + + + + + + + + + + - + - + - - + + - - + + - - + + - + - + - + @@ -795,7 +806,7 @@ - + @@ -882,7 +893,7 @@ - + @@ -912,19 +923,25 @@ - + + + + + + + - + - + diff --git a/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift new file mode 100644 index 000000000..5af73c332 --- /dev/null +++ b/iOS/MainTimeline/Cells/MainTimelineCollectionViewCell.swift @@ -0,0 +1,280 @@ +// +// 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! + @IBOutlet var topSeparator: UIView! + + 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 = (state.isSelected && !state.isSwiped) ? .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 = (state.isSelected && !state.isSwiped) ? .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 + return active + } + + + private func setIconImage(_ iconImage: IconImage?, with size: IconSize) { + if feedIcon != nil { + updateIconViewSizeConstraints(to: size.size) + feedIcon!.iconImage = iconImage + } + } + + 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 state.isSwiped && state.isSelected { + return .white + } else if state.isSwiped && !state.isSelected { + return .label + } else if !state.isSwiped && state.isSelected { + 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 ? -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 + 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) + + self.backgroundConfiguration = backgroundConfig + } + +} + 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/MainTimelineModernViewController.swift similarity index 67% rename from iOS/MainTimeline/MainTimelineViewController.swift rename to iOS/MainTimeline/MainTimelineModernViewController.swift index ce992ce1c..d4842b59f 100644 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ b/iOS/MainTimeline/MainTimelineModernViewController.swift @@ -1,9 +1,9 @@ // -// MainTimelineViewController.swift -// NetNewsWire +// MainTimelineModernViewController.swift +// NetNewsWire-iOS // -// Created by Maurice Parker on 4/8/19. -// Copyright © 2019 Ranchero Software. All rights reserved. +// Created by Stuart Breckenridge on 25/01/2026. +// Copyright © 2026 Ranchero Software. All rights reserved. // import UIKit @@ -14,7 +14,9 @@ import RSWeb import Account import Articles -final class MainTimelineViewController: UITableViewController, UndoableCommandRunner { + +final class MainTimelineModernViewController: UIViewController, UndoableCommandRunner { + struct CellIdentifier { static let standard = "MainTimelineCellStandard" static let standardIndex0 = "MainTimelineCellIndexZero" @@ -22,24 +24,15 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu static let iconIndex0 = "MainTimelineCellIconIndexZero" } + // MARK: Private Variables 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 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 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 @@ -101,18 +94,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu 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() @@ -139,70 +121,49 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu 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 } - - 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 - } + + // 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: "MainTimelineModernViewController") + + // 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! + + + override func viewDidLoad() { + super.viewDidLoad() + + addNotificationObservers() + configureCollectionView() + configureSearchController() 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) + collectionView.refreshControl = UIRefreshControl() + collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) configureToolbar() resetUI(resetScroll: true) @@ -210,7 +171,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu // 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) + self.collectionView.scrollToItem(at: restoreIndexPath, at: .centeredVertically, animated: false) } } @@ -221,12 +182,14 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu gesture.allowedScrollTypesMask = [] navigationItem.title = nil // Don’t let "Timeline" accidentally show + 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 @@ -241,7 +204,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu } override func viewDidAppear(_ animated: Bool) { - Self.logger.debug("MainTimelineViewController: viewDidAppear") + Self.logger.debug("MainTimelineModernViewController: viewDidAppear") super.viewDidAppear(true) isTimelineViewControllerPending = false @@ -252,15 +215,167 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu } if traitCollection.userInterfaceIdiom == .phone { if coordinator?.currentArticle != nil { - if let indexPath = tableView.indexPathForSelectedRow { - tableView.deselectRow(at: indexPath, animated: true) + if let indexPath = collectionView.indexPathsForSelectedItems?.first { + collectionView.deselectItem(at: indexPath, animated: true) } coordinator?.selectArticle(nil) } } } - // MARK: - Actions + 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 { + 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) + } + } + } + } + } + + 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("MainTimelineModernViewController: reinitializeArticles") + resetUI(resetScroll: resetScroll) + } + + func reloadArticles(animated: Bool) { + Self.logger.debug("MainTimelineModernViewController: reloadArticles") + applyChanges(animated: animated) + } + + func updateArticleSelection(animations: Animations) { + 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) + } + + updateUI() + } + + func updateUI() { + Self.logger.debug("MainTimelineModernViewController: 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("MainTimelineModernViewController: focus") + becomeFirstResponder() + } + + // MARK: - Reloading + + func queueReloadAvailableCells() { + CoalescingQueue.standard.add(self, #selector(reloadVisibleCells)) + } + + @objc private func reloadVisibleCells() { + Self.logger.debug("MainTimelineModernViewController: reloadVisibleCells") + guard isViewLoaded, view.window != nil else { + return + } + let indexPaths = collectionView.indexPathsForVisibleItems + + let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } + reloadCells(visibleArticles) + } + + private func reloadCells(_ articles: [Article]) { + Self.logger.debug("MainTimelineModernViewController: reloadCells") + guard !articles.isEmpty else { + return + } + + var snapshot = dataSource.snapshot() + snapshot.reloadItems(articles) + 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) { + 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) @@ -292,7 +407,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu } if sender is UIKeyCommand { - guard let indexPath = tableView.indexPathForSelectedRow, let contentView = tableView.cellForRow(at: indexPath)?.contentView else { + guard let indexPath = collectionView.indexPathsForSelectedItems?.first, let contentView = collectionView.cellForItem(at: indexPath)?.contentView else { return } @@ -307,245 +422,61 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu coordinator?.selectFirstUnread() } - @objc func refreshAccounts(_ sender: Any) { - refreshControl?.endRefreshing() + /* + // MARK: - Navigation - // 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)) - } - } + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destination. + // Pass the selected object to the new view controller. + } + */ - // MARK: - Keyboard shortcuts +} - @objc func selectNextUp(_ sender: Any?) { - assert(coordinator != nil) - coordinator?.selectPrevArticle() - } - @objc func selectNextDown(_ sender: Any?) { - assert(coordinator != nil) - coordinator?.selectNextArticle() - } +// MARK: - UICollectionViewDelegate - @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") +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: - 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 - + + 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: indexPath) { + if let action = self.markAboveAsReadAction(article, indexPath: firstIndex) { markActions.append(action) } - if let action = self.markBelowAsReadAction(article, indexPath: indexPath) { + 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: indexPath) { + 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) @@ -556,264 +487,271 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu 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) { + + if let action = self.shareAction(article, indexPath: firstIndex) { menuElements.append(UIMenu(title: "", options: .displayInline, children: [action])) } - + return UIMenu(title: "", children: menuElements) - + }) - } - - override func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { + + func collectionView(_ collectionView: UICollectionView, contextMenuConfiguration configuration: UIContextMenuConfiguration, highlightPreviewForItemAt indexPath: IndexPath) -> 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 { + let cell = collectionView.cellForItem(at: IndexPath(row: row, section: 0)) else { return nil } - + 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) } - - 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 + + + 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 = .clear + parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, + cornerRadius: 20) + return UITargetedPreview(view: cell, parameters: parameters) + } + + +} - let visibleArticles = indexPaths.compactMap { dataSource.itemIdentifier(for: $0) } - let visibleUpdatedArticles = visibleArticles.filter { articleIDs.contains($0.articleID) } +// MARK: Private API +private extension MainTimelineModernViewController { + + 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.showsSeparators = false + 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 + /// 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) + } + + 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) - 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") + moreAction.image = Assets.Images.more + moreAction.backgroundColor = UIColor.systemGray + + actions.append(starAction) + actions.append(moreAction) - guard isViewLoaded else { - return - } - guard let feed = note.userInfo?[UserInfoKey.feed] as? Feed else { - return - } + let config = UISwipeActionsConfiguration(actions: actions) + config.performsFirstActionWithFullSwipe = false - 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 + return config } + config.leadingSwipeActionsConfigurationProvider = { [unowned self] indexPath in + 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") : + NSLocalizedString("Mark as Read", comment: "Mark as Read") - for indexPath in indexPaths { - guard let article = dataSource.itemIdentifier(for: indexPath), let authors = article.authors, !authors.isEmpty else { - continue + let readAction = UIContextualAction(style: .normal, title: readTitle) { [weak self] _, _, completion in + /// 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) } - for author in authors { - if author.avatarURL == avatarURL, let cell = tableView.cellForRow(at: indexPath) as? MainTimelineCell, let image = iconImageFor(article) { - cell.setIconImage(image) + + readAction.image = article.status.read ? Assets.Images.circleClosed : Assets.Images.circleOpen + readAction.backgroundColor = Assets.Colors.primaryAccent + actions.append(readAction) + + let config = UISwipeActionsConfiguration(actions: actions) + config.performsFirstActionWithFullSwipe = true + return config + } + + collectionView.refreshControl = UIRefreshControl() + collectionView.refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) + collectionView.contentInsetAdjustmentBehavior = .automatic + + let layout = UICollectionViewCompositionalLayout.list(using: config) + layout.configuration.contentInsetsReference = .safeArea + collectionView.collectionViewLayout = layout + } + + 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: CellIdentifier.iconIndex0, for: indexPath) as! MainTimelineCollectionViewCell + cell.cellData = cellData + return cell + } else { + 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: CellIdentifier.standardIndex0, for: indexPath) as! MainTimelineCollectionViewCell + cell.cellData = cellData + return cell + } else { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier.standard, 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() } - - @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) @@ -840,12 +778,12 @@ private extension MainTimelineViewController { filterButton.accLabelText = NSLocalizedString("Filter Read Articles", comment: "Filter Read Articles") } - tableView.selectRow(at: nil, animated: false, scrollPosition: .top) + 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 { - tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false) + //collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: .top) } } @@ -871,12 +809,7 @@ private extension MainTimelineViewController { } func applyChanges(animated: Bool, completion: (() -> Void)? = nil) { - if (articles?.count ?? 0) == 0 { - tableView.rowHeight = tableView.estimatedRowHeight - } else { - tableView.rowHeight = UITableView.automaticDimension - } - + Self.logger.debug("MainTimelineModernViewController: applyChanges") var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([0]) snapshot.appendItems(articles ?? ArticleArray(), toSection: 0) @@ -886,48 +819,177 @@ private extension MainTimelineViewController { completion?() } } + + - func makeDataSource() -> UITableViewDiffableDataSource { - let dataSource: UITableViewDiffableDataSource = - MainTimelineDataSource(tableView: tableView) { [weak self] tableView, indexPath, article in - guard let self else { + + +} + +// MARK: - Notifications API +private extension MainTimelineModernViewController { + @objc dynamic func unreadCountDidChange(_ notification: Notification) { + Self.logger.debug("MainTimelineModernViewController: unreadCountDidChange") + updateUI() + } + + @objc func statusesDidChange(_ note: Notification) { + Self.logger.debug("MainTimelineModernViewController: 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) } + reloadCells(visibleUpdatedArticles) + } + + @objc func feedIconDidBecomeAvailable(_ note: Notification) { + Self.logger.debug("MainTimelineModernViewController: 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("MainTimelineModernViewController: 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 } - 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 + for author in authors { + if author.avatarURL == avatarURL { + return article } - }() - - // 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() + reloadCells(articlesToReload) } + @objc func faviconDidBecomeAvailable(_ note: Notification) { + Self.logger.debug("MainTimelineModernViewController: 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 + } + reloadCells(articlesToReload) + } + + func userDefaultsDidChange() { + Self.logger.debug("MainTimelineModernViewController: userDefaultsDidChange") + + if self.numberOfTextLines != AppDefaults.shared.timelineNumberOfLines || self.iconSize != AppDefaults.shared.timelineIconSize { + self.numberOfTextLines = AppDefaults.shared.timelineNumberOfLines + self.iconSize = AppDefaults.shared.timelineIconSize + self.reloadVisibleCells() + } + self.updateToolbar() + } + + @objc func contentSizeCategoryDidChange(_ note: Notification) { + Self.logger.debug("MainTimelineModernViewController: contentSizeCategoryDidChange") + reloadVisibleCells() + } + + @objc func displayNameDidChange(_ note: Notification) { + Self.logger.debug("MainTimelineModernViewController: displayNameDidChange") + updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "") + } + + @objc func willEnterForeground(_ note: Notification) { + Self.logger.debug("MainTimelineModernViewController: willEnterForeground") + updateUI() + } + + @objc func scrollPositionDidChange() { + Self.logger.debug("MainTimelineModernViewController: scrollPositionDidChange") + timelineMiddleIndexPath = collectionView.middleVisibleRow() + } + +} + +extension MainTimelineModernViewController: UISearchControllerDelegate { + + func willPresentSearchController(_ searchController: UISearchController) { + coordinator?.beginSearching() + searchController.searchBar.showsScopeBar = true + } + + func willDismissSearchController(_ searchController: UISearchController) { + coordinator?.endSearching() + searchController.searchBar.showsScopeBar = false + updateToolbar() + } + +} + +extension MainTimelineModernViewController: UISearchResultsUpdating { + + func updateSearchResults(for searchController: UISearchController) { + let searchScope = SearchScope(rawValue: searchController.searchBar.selectedScopeButtonIndex)! + searchArticles(searchController.searchBar.text!, searchScope) + } + +} + +extension MainTimelineModernViewController: UISearchBarDelegate { + func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { + let searchScope = SearchScope(rawValue: selectedScope)! + searchArticles(searchBar.text!, searchScope) + } +} + +// MARK: Article Actions +extension MainTimelineModernViewController { func toggleRead(_ article: Article) { assert(coordinator != nil) coordinator?.toggleRead(article) @@ -978,7 +1040,7 @@ private extension MainTimelineViewController { } func markAboveAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? { - guard canMarkAboveAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + guard canMarkAboveAsRead(for: article), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { return nil } @@ -1003,7 +1065,7 @@ private extension MainTimelineViewController { } func markBelowAsReadAction(_ article: Article, indexPath: IndexPath) -> UIAction? { - guard canMarkBelowAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + guard canMarkBelowAsRead(for: article), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { return nil } @@ -1018,7 +1080,7 @@ private extension MainTimelineViewController { } func markAboveAsReadAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { - guard canMarkAboveAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + guard canMarkAboveAsRead(for: article), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { return nil } @@ -1037,7 +1099,7 @@ private extension MainTimelineViewController { } func markBelowAsReadAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { - guard canMarkBelowAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + guard canMarkBelowAsRead(for: article), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { return nil } @@ -1100,7 +1162,7 @@ private extension MainTimelineViewController { } let articles = Array(fetchedArticles) - guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + guard articles.canMarkAllAsRead(), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { return nil } @@ -1122,7 +1184,7 @@ private extension MainTimelineViewController { } let articles = Array(fetchedArticles) - guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else { + guard articles.canMarkAllAsRead(), let contentView = self.collectionView.cellForItem(at: indexPath)?.contentView else { return nil } @@ -1191,7 +1253,7 @@ private extension MainTimelineViewController { 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 { + guard let cell = collectionView.cellForItem(at: indexPath) else { return } let popoverController = activityViewController.popoverPresentationController @@ -1219,5 +1281,5 @@ private extension MainTimelineViewController { } return action } - } + diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index 89ede5054..acf0dc35f 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: 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? MainTimelineViewController + self.mainTimelineViewController = rootSplitViewController.viewController(for: .supplementary) as? MainTimelineModernViewController self.mainTimelineViewController?.coordinator = self self.mainTimelineViewController?.navigationController?.delegate = self @@ -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 } diff --git a/iOS/Settings/TimelineCustomizerTableViewController.swift b/iOS/Settings/TimelineCustomizerTableViewController.swift index 5a555824e..06acd6a79 100644 --- a/iOS/Settings/TimelineCustomizerTableViewController.swift +++ b/iOS/Settings/TimelineCustomizerTableViewController.swift @@ -85,7 +85,7 @@ final class TimelineCustomizerTableViewController: UITableViewController { } if indexPath.section == 2 { - let cell = tableView.dequeueReusableCell(withIdentifier: MainTimelineViewController.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", @@ -99,7 +99,7 @@ final class TimelineCustomizerTableViewController: UITableViewController { } if indexPath.section == 3 { - let cell = tableView.dequeueReusableCell(withIdentifier: MainTimelineViewController.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",