From 59a4d379258e3e1bb70ca2d7581fa37c0dfc72ad Mon Sep 17 00:00:00 2001 From: Stuart Breckenridge Date: Fri, 15 Aug 2025 20:22:44 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20Removes=20unused=20code=20(fixes?= =?UTF-8?q?=20#4720)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iOS/MainFeed/Cell/MainFeedTableViewCell.swift | 232 --- .../Cell/MainFeedTableViewCellLayout.swift | 148 -- .../Cell/MainFeedTableViewSectionHeader.swift | 213 --- ...MainFeedTableViewSectionHeaderLayout.swift | 90 -- .../Cell/MainFeedUnreadCountView.swift | 123 -- .../MainFeedRowIdentifier.swift | 0 .../MainFeedViewController+Drag.swift | 34 - .../MainFeedViewController+Drop.swift | 166 --- iOS/MainFeed/MainFeedViewController.swift | 1315 ----------------- iOS/MainTimeline/MainTimelineTitleView.swift | 64 - iOS/MainTimeline/MainTimelineTitleView.xib | 61 - .../MainTimelineUnreadCountView.swift | 39 - .../MainTimelineViewController.swift | 20 +- 13 files changed, 2 insertions(+), 2503 deletions(-) delete mode 100644 iOS/MainFeed/Cell/MainFeedTableViewCell.swift delete mode 100644 iOS/MainFeed/Cell/MainFeedTableViewCellLayout.swift delete mode 100644 iOS/MainFeed/Cell/MainFeedTableViewSectionHeader.swift delete mode 100644 iOS/MainFeed/Cell/MainFeedTableViewSectionHeaderLayout.swift delete mode 100644 iOS/MainFeed/Cell/MainFeedUnreadCountView.swift rename iOS/MainFeed/{Cell => Collection View Cells}/MainFeedRowIdentifier.swift (100%) delete mode 100644 iOS/MainFeed/MainFeedViewController+Drag.swift delete mode 100644 iOS/MainFeed/MainFeedViewController+Drop.swift delete mode 100644 iOS/MainFeed/MainFeedViewController.swift delete mode 100644 iOS/MainTimeline/MainTimelineTitleView.swift delete mode 100644 iOS/MainTimeline/MainTimelineTitleView.xib delete mode 100644 iOS/MainTimeline/MainTimelineUnreadCountView.swift diff --git a/iOS/MainFeed/Cell/MainFeedTableViewCell.swift b/iOS/MainFeed/Cell/MainFeedTableViewCell.swift deleted file mode 100644 index 1a530eece..000000000 --- a/iOS/MainFeed/Cell/MainFeedTableViewCell.swift +++ /dev/null @@ -1,232 +0,0 @@ -// -// MainFeedTableViewCell.swift -// NetNewsWire -// -// Created by Brent Simmons on 8/1/15. -// Copyright © 2015 Ranchero Software, LLC. All rights reserved. -// - -import UIKit -import RSCore -import Account -import RSTree - -protocol MainFeedTableViewCellDelegate: AnyObject { - func mainFeedTableViewCellDisclosureDidToggle(_ sender: MainFeedTableViewCell, expanding: Bool) -} - -class MainFeedTableViewCell : VibrantTableViewCell { - - weak var delegate: MainFeedTableViewCellDelegate? - - override var accessibilityLabel: String? { - set {} - get { - if unreadCount > 0 { - let unreadLabel = NSLocalizedString("unread", comment: "Unread label for accessibility") - return "\(name) \(unreadCount) \(unreadLabel)" - } else { - return name - } - } - } - - var iconImage: IconImage? { - didSet { - iconView.iconImage = iconImage - } - } - - var isDisclosureAvailable = false { - didSet { - if isDisclosureAvailable != oldValue { - setNeedsLayout() - } - } - } - - var isSeparatorShown = true { - didSet { - if isSeparatorShown != oldValue { - if isSeparatorShown { - showView(bottomSeparatorView) - } else { - hideView(bottomSeparatorView) - } - } - } - } - - var unreadCount: Int { - get { - return unreadCountView.unreadCount - } - set { - if unreadCountView.unreadCount != newValue { - unreadCountView.unreadCount = newValue - unreadCountView.isHidden = (newValue < 1) - setNeedsLayout() - } - } - } - - var name: String { - get { - return titleView.text ?? "" - } - set { - if titleView.text != newValue { - titleView.text = newValue - setNeedsLayout() - } - } - } - - private let titleView: UILabel = { - let label = NonIntrinsicLabel() - label.numberOfLines = 0 - label.allowsDefaultTighteningForTruncation = false - label.adjustsFontForContentSizeCategory = true - label.lineBreakMode = .byTruncatingTail - label.font = .preferredFont(forTextStyle: .body) - return label - }() - - private let iconView = IconView() - - private let bottomSeparatorView: UIView = { - let view = UIView() - view.backgroundColor = UIColor.separator - view.alpha = 0.5 - return view - }() - - private var isDisclosureExpanded = false - private var disclosureButton: UIButton? - private var unreadCountView = MainFeedUnreadCountView(frame: CGRect.zero) - private var isShowingEditControl = false - - required init?(coder: NSCoder) { - super.init(coder: coder) - commonInit() - } - - func setDisclosure(isExpanded: Bool, animated: Bool) { - isDisclosureExpanded = isExpanded - let duration = animated ? 0.3 : 0.0 - - UIView.animate(withDuration: duration) { - if self.isDisclosureExpanded { - self.disclosureButton?.accessibilityLabel = NSLocalizedString("Collapse Folder", comment: "Collapse Folder") - self.disclosureButton?.imageView?.transform = CGAffineTransform(rotationAngle: 1.570796) - } else { - self.disclosureButton?.accessibilityLabel = NSLocalizedString("Expand Folder", comment: "Expand Folder") - self.disclosureButton?.imageView?.transform = CGAffineTransform(rotationAngle: 0) - } - } - } - - override func applyThemeProperties() { - super.applyThemeProperties() - } - - override func willTransition(to state: UITableViewCell.StateMask) { - super.willTransition(to: state) - isShowingEditControl = state.contains(.showingEditControl) - } - - override func sizeThatFits(_ size: CGSize) -> CGSize { - let layout = MainFeedTableViewCellLayout(cellWidth: bounds.size.width, insets: safeAreaInsets, label: titleView, unreadCountView: unreadCountView, showingEditingControl: isShowingEditControl, indent: indentationLevel == 1, shouldShowDisclosure: isDisclosureAvailable) - return CGSize(width: bounds.width, height: layout.height) - } - - override func layoutSubviews() { - super.layoutSubviews() - let layout = MainFeedTableViewCellLayout(cellWidth: bounds.size.width, insets: safeAreaInsets, label: titleView, unreadCountView: unreadCountView, showingEditingControl: isShowingEditControl, indent: indentationLevel == 1, shouldShowDisclosure: isDisclosureAvailable) - layoutWith(layout) - } - - @objc func buttonPressed(_ sender: UIButton) { - if isDisclosureAvailable { - setDisclosure(isExpanded: !isDisclosureExpanded, animated: true) - delegate?.mainFeedTableViewCellDisclosureDidToggle(self, expanding: isDisclosureExpanded) - } - } - - override func updateVibrancy(animated: Bool) { - super.updateVibrancy(animated: animated) - - let iconTintColor: UIColor - if isHighlighted || isSelected { - iconTintColor = AppAssets.vibrantTextColor - } else { - if let preferredColor = iconImage?.preferredColor { - iconTintColor = UIColor(cgColor: preferredColor) - } else { - iconTintColor = AppAssets.secondaryAccentColor - } - } - - if animated { - UIView.animate(withDuration: Self.duration) { - self.iconView.tintColor = iconTintColor - } - } else { - self.iconView.tintColor = iconTintColor - } - - updateLabelVibrancy(titleView, color: labelColor, animated: animated) - } - -} - -private extension MainFeedTableViewCell { - - func commonInit() { - addSubviewAtInit(unreadCountView) - addSubviewAtInit(iconView) - addSubviewAtInit(titleView) - addDisclosureView() - addSubviewAtInit(bottomSeparatorView) - } - - func addDisclosureView() { - disclosureButton = NonIntrinsicButton(type: .roundedRect) - disclosureButton!.addTarget(self, action: #selector(buttonPressed(_:)), for: UIControl.Event.touchUpInside) - disclosureButton?.setImage(AppAssets.disclosureImage, for: .normal) - disclosureButton?.tintColor = AppAssets.controlBackgroundColor - disclosureButton?.imageView?.contentMode = .center - disclosureButton?.imageView?.clipsToBounds = false - if #available(iOS 13.4, *) { - disclosureButton?.addInteraction(UIPointerInteraction()) - } - addSubviewAtInit(disclosureButton!) - } - - func addSubviewAtInit(_ view: UIView) { - addSubview(view) - view.translatesAutoresizingMaskIntoConstraints = false - } - - func layoutWith(_ layout: MainFeedTableViewCellLayout) { - iconView.setFrameIfNotEqual(layout.faviconRect) - titleView.setFrameIfNotEqual(layout.titleRect) - unreadCountView.setFrameIfNotEqual(layout.unreadCountRect) - disclosureButton?.setFrameIfNotEqual(layout.disclosureButtonRect) - disclosureButton?.isHidden = !isDisclosureAvailable - bottomSeparatorView.setFrameIfNotEqual(layout.separatorRect) - } - - func hideView(_ view: UIView) { - if !view.isHidden { - view.isHidden = true - } - } - - func showView(_ view: UIView) { - if view.isHidden { - view.isHidden = false - } - } - -} diff --git a/iOS/MainFeed/Cell/MainFeedTableViewCellLayout.swift b/iOS/MainFeed/Cell/MainFeedTableViewCellLayout.swift deleted file mode 100644 index a1d84f04e..000000000 --- a/iOS/MainFeed/Cell/MainFeedTableViewCellLayout.swift +++ /dev/null @@ -1,148 +0,0 @@ -// -// MainFeedTableViewCellLayout.swift -// NetNewsWire -// -// Created by Brent Simmons on 11/24/17. -// Copyright © 2017 Ranchero Software. All rights reserved. -// - -import UIKit -import RSCore - -struct MainFeedTableViewCellLayout { - - private static let indentWidth = CGFloat(integerLiteral: 42) - private static let editingControlIndent = CGFloat(integerLiteral: 40) - private static let imageSize = CGSize(width: 24, height: 24) - private static let imageMarginRight = CGFloat(integerLiteral: 11) - private static let labelMarginRight = CGFloat(integerLiteral: 8) - private static let unreadCountMarginRight = CGFloat(integerLiteral: 16) - private static let disclosureButtonSize = CGSize(width: 44, height: 44) - private static let verticalPadding = CGFloat(integerLiteral: 11) - - private static let minRowHeight = CGFloat(integerLiteral: 44) - - static let faviconCornerRadius = CGFloat(integerLiteral: 2) - - let faviconRect: CGRect - let titleRect: CGRect - let unreadCountRect: CGRect - let disclosureButtonRect: CGRect - let separatorRect: CGRect - - let height: CGFloat - - init(cellWidth: CGFloat, insets: UIEdgeInsets, label: UILabel, unreadCountView: MainFeedUnreadCountView, showingEditingControl: Bool, indent: Bool, shouldShowDisclosure: Bool) { - - var initialIndent = insets.left - if indent { - initialIndent += MainFeedTableViewCellLayout.indentWidth - } - let bounds = CGRect(x: initialIndent, y: 0.0, width: floor(cellWidth - initialIndent - insets.right), height: 0.0) - - // Disclosure Button - var rDisclosure = CGRect.zero - if shouldShowDisclosure { - rDisclosure.size = MainFeedTableViewCellLayout.disclosureButtonSize - rDisclosure.origin.x = bounds.origin.x - } - - // Favicon - var rFavicon = CGRect.zero - if !shouldShowDisclosure { - let x = bounds.origin.x - let y = UIFontMetrics.default.scaledValue(for: MainFeedTableViewCellLayout.verticalPadding) + - label.font.lineHeight / 2.0 - - MainFeedTableViewCellLayout.imageSize.height / 2.0 - rFavicon = CGRect(x: x, y: y, width: MainFeedTableViewCellLayout.imageSize.width, height: MainFeedTableViewCellLayout.imageSize.height) - } - - // Unread Count - let unreadCountSize = unreadCountView.contentSize - let unreadCountIsHidden = unreadCountView.unreadCount < 1 - - var rUnread = CGRect.zero - if !unreadCountIsHidden { - rUnread.size = unreadCountSize - rUnread.origin.x = bounds.maxX - (MainFeedTableViewCellLayout.unreadCountMarginRight + unreadCountSize.width) - } - - // Title - var rLabelx = insets.left + MainFeedTableViewCellLayout.disclosureButtonSize.width - if !shouldShowDisclosure { - rLabelx = rLabelx + MainFeedTableViewCellLayout.imageSize.width + MainFeedTableViewCellLayout.imageMarginRight - } - let rLabely = UIFontMetrics.default.scaledValue(for: MainFeedTableViewCellLayout.verticalPadding) - - var labelWidth = CGFloat.zero - if !unreadCountIsHidden { - labelWidth = cellWidth - (rLabelx + MainFeedTableViewCellLayout.labelMarginRight + (cellWidth - rUnread.minX)) - } else { - labelWidth = cellWidth - (rLabelx + MainFeedTableViewCellLayout.labelMarginRight) - } - - let labelSizeInfo = MultilineUILabelSizer.size(for: label.text ?? "", font: label.font, numberOfLines: 0, width: Int(floor(labelWidth))) - - // Now that we've got everything (especially the label) computed without the editing controls, update for them. - // We do this because we don't want the row height to change when the editing controls are brought out. We will - // handle the missing space, but removing it from the label and truncating. - if showingEditingControl { - rDisclosure.origin.x += MainFeedTableViewCellLayout.editingControlIndent - rFavicon.origin.x += MainFeedTableViewCellLayout.editingControlIndent - rLabelx += MainFeedTableViewCellLayout.editingControlIndent - if !unreadCountIsHidden { - rUnread.origin.x -= MainFeedTableViewCellLayout.editingControlIndent - labelWidth = cellWidth - (rLabelx + MainFeedTableViewCellLayout.labelMarginRight + (cellWidth - rUnread.minX)) - } else { - labelWidth = cellWidth - (rLabelx + MainFeedTableViewCellLayout.labelMarginRight + MainFeedTableViewCellLayout.editingControlIndent) - } - } - - var rLabel = CGRect(x: rLabelx, y: rLabely, width: labelWidth, height: labelSizeInfo.size.height) - - // Determine cell height - let paddedLabelHeight = rLabel.maxY + UIFontMetrics.default.scaledValue(for: MainFeedTableViewCellLayout.verticalPadding) - let maxGraphicsHeight = [rFavicon, rUnread, rDisclosure].maxY() - var cellHeight = max(paddedLabelHeight, maxGraphicsHeight) - if cellHeight < MainFeedTableViewCellLayout.minRowHeight { - cellHeight = MainFeedTableViewCellLayout.minRowHeight - } - - // Center in Cell - let newBounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: cellHeight) - if !unreadCountIsHidden { - rUnread = MainFeedTableViewCellLayout.centerVertically(rUnread, newBounds) - } - if shouldShowDisclosure { - rDisclosure = MainFeedTableViewCellLayout.centerVertically(rDisclosure, newBounds) - } - - // Small fonts and the Favicon need centered if we hit the minimum row height - if cellHeight == MainFeedTableViewCellLayout.minRowHeight { - rLabel = MainFeedTableViewCellLayout.centerVertically(rLabel, newBounds) - rFavicon = MainFeedTableViewCellLayout.centerVertically(rFavicon, newBounds) - } - - // Separator Insets - let separatorInset = MainFeedTableViewCellLayout.disclosureButtonSize.width - separatorRect = CGRect(x: separatorInset, y: cellHeight - 0.5, width: cellWidth - separatorInset, height: 0.5) - - // Assign the properties - self.height = cellHeight - self.faviconRect = rFavicon - self.unreadCountRect = rUnread - self.disclosureButtonRect = rDisclosure - self.titleRect = rLabel - - } - - // Ideally this will be implemented in RSCore (see RSGeometry) - static func centerVertically(_ originalRect: CGRect, _ containerRect: CGRect) -> CGRect { - var result = originalRect - result.origin.y = containerRect.midY - (result.height / 2.0) - result = result.integral - result.size = originalRect.size - return result - } - -} diff --git a/iOS/MainFeed/Cell/MainFeedTableViewSectionHeader.swift b/iOS/MainFeed/Cell/MainFeedTableViewSectionHeader.swift deleted file mode 100644 index d113dc0b8..000000000 --- a/iOS/MainFeed/Cell/MainFeedTableViewSectionHeader.swift +++ /dev/null @@ -1,213 +0,0 @@ -// -// MainTableViewSectionHeader.swift -// NetNewsWire -// -// Created by Maurice Parker on 4/18/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit - -protocol MainFeedTableViewSectionHeaderDelegate { - func mainFeedTableViewSectionHeaderDisclosureDidToggle(_ sender: MainFeedTableViewSectionHeader) -} - -class MainFeedTableViewSectionHeader: UITableViewHeaderFooterView { - - var delegate: MainFeedTableViewSectionHeaderDelegate? - - override var accessibilityLabel: String? { - set {} - get { - if unreadCount > 0 { - let unreadLabel = NSLocalizedString("unread", comment: "Unread label for accessibility") - return "\(name) \(unreadCount) \(unreadLabel) \(expandedStateMessage) " - } else { - return "\(name) \(expandedStateMessage) " - } - } - } - - private var expandedStateMessage: String { - set {} - get { - if disclosureExpanded { - return NSLocalizedString("Expanded", comment: "Disclosure button expanded state for accessibility") - } - return NSLocalizedString("Collapsed", comment: "Disclosure button collapsed state for accessibility") - } - } - - var unreadCount: Int { - get { - return unreadCountView.unreadCount - } - set { - if unreadCountView.unreadCount != newValue { - unreadCountView.unreadCount = newValue - updateUnreadCountView() - setNeedsLayout() - } - } - } - - var name: String { - get { - return titleView.text ?? "" - } - set { - if titleView.text != newValue { - titleView.text = newValue - setNeedsLayout() - } - } - } - - var disclosureExpanded = false { - didSet { - updateExpandedState(animate: true) - updateUnreadCountView() - } - } - - var isLastSection = false - - private let titleView: UILabel = { - let label = NonIntrinsicLabel() - label.numberOfLines = 0 - label.allowsDefaultTighteningForTruncation = false - label.adjustsFontForContentSizeCategory = true - label.font = .preferredFont(forTextStyle: .body) - return label - }() - - private let unreadCountView = MainFeedUnreadCountView(frame: CGRect.zero) - - private lazy var disclosureButton: UIButton = { - let button = NonIntrinsicButton() - button.tintColor = UIColor.tertiaryLabel - button.setImage(AppAssets.disclosureImage, for: .normal) - button.contentMode = .center - if #available(iOS 13.4, *) { - button.addInteraction(UIPointerInteraction()) - } - button.addTarget(self, action: #selector(toggleDisclosure), for: .touchUpInside) - return button - }() - - private let topSeparatorView: UIView = { - let view = UIView() - view.backgroundColor = UIColor.separator - return view - }() - - private let bottomSeparatorView: UIView = { - let view = UIView() - view.backgroundColor = UIColor.separator - return view - }() - - override init(reuseIdentifier: String?) { - super.init(reuseIdentifier: reuseIdentifier) - commonInit() - } - - required init?(coder: NSCoder) { - super.init(coder: coder) - commonInit() - } - - override func sizeThatFits(_ size: CGSize) -> CGSize { - let layout = MainFeedTableViewSectionHeaderLayout(cellWidth: size.width, insets: safeAreaInsets, label: titleView, unreadCountView: unreadCountView) - return CGSize(width: bounds.width, height: layout.height) - - } - - override func layoutSubviews() { - super.layoutSubviews() - let layout = MainFeedTableViewSectionHeaderLayout(cellWidth: contentView.bounds.size.width, - insets: contentView.safeAreaInsets, - label: titleView, - unreadCountView: unreadCountView) - layoutWith(layout) - } - -} - -private extension MainFeedTableViewSectionHeader { - - @objc func toggleDisclosure() { - delegate?.mainFeedTableViewSectionHeaderDisclosureDidToggle(self) - } - - func commonInit() { - addSubviewAtInit(unreadCountView) - addSubviewAtInit(titleView) - addSubviewAtInit(disclosureButton) - updateExpandedState(animate: false) - addBackgroundView() - addSubviewAtInit(topSeparatorView) - addSubviewAtInit(bottomSeparatorView) - } - - func updateExpandedState(animate: Bool) { - if !isLastSection && self.disclosureExpanded { - self.bottomSeparatorView.isHidden = false - } - - let duration = animate ? 0.3 : 0.0 - - UIView.animate( - withDuration: duration, - animations: { - if self.disclosureExpanded { - self.disclosureButton.transform = CGAffineTransform(rotationAngle: 1.570796) - } else { - self.disclosureButton.transform = CGAffineTransform(rotationAngle: 0) - } - }, completion: { _ in - if !self.isLastSection && !self.disclosureExpanded { - self.bottomSeparatorView.isHidden = true - } - }) - } - - func updateUnreadCountView() { - if !disclosureExpanded && unreadCount > 0 { - UIView.animate(withDuration: 0.3) { - self.unreadCountView.alpha = 1 - } - } else { - UIView.animate(withDuration: 0.3) { - self.unreadCountView.alpha = 0 - } - } - } - - func addSubviewAtInit(_ view: UIView) { - contentView.addSubview(view) - view.translatesAutoresizingMaskIntoConstraints = false - } - - func layoutWith(_ layout: MainFeedTableViewSectionHeaderLayout) { - titleView.setFrameIfNotEqual(layout.titleRect) - unreadCountView.setFrameIfNotEqual(layout.unreadCountRect) - disclosureButton.setFrameIfNotEqual(layout.disclosureButtonRect) - - let x = -safeAreaInsets.left - let width = safeAreaInsets.left + safeAreaInsets.right + frame.width - let height = 0.33 - - let top = CGRect(x: x, y: 0, width: width, height: height) - topSeparatorView.setFrameIfNotEqual(top) - - let bottom = CGRect(x: x, y: frame.height - height, width: width, height: height) - bottomSeparatorView.setFrameIfNotEqual(bottom) - } - - func addBackgroundView() { - self.backgroundView = UIView(frame: self.bounds) - self.backgroundView?.backgroundColor = AppAssets.sectionHeaderColor - } - -} diff --git a/iOS/MainFeed/Cell/MainFeedTableViewSectionHeaderLayout.swift b/iOS/MainFeed/Cell/MainFeedTableViewSectionHeaderLayout.swift deleted file mode 100644 index 758383e09..000000000 --- a/iOS/MainFeed/Cell/MainFeedTableViewSectionHeaderLayout.swift +++ /dev/null @@ -1,90 +0,0 @@ -// -// MainFeedTableViewSectionHeaderLayout.swift -// NetNewsWire-iOS -// -// Created by Maurice Parker on 11/5/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit -import RSCore - -struct MainFeedTableViewSectionHeaderLayout { - - private static let labelMarginRight = CGFloat(integerLiteral: 8) - private static let unreadCountMarginRight = CGFloat(integerLiteral: 16) - private static let disclosureButtonSize = CGSize(width: 44, height: 44) - private static let verticalPadding = CGFloat(integerLiteral: 11) - - private static let minRowHeight = CGFloat(integerLiteral: 44) - - let titleRect: CGRect - let unreadCountRect: CGRect - let disclosureButtonRect: CGRect - - let height: CGFloat - - init(cellWidth: CGFloat, insets: UIEdgeInsets, label: UILabel, unreadCountView: MainFeedUnreadCountView) { - - let bounds = CGRect(x: insets.left, y: 0.0, width: floor(cellWidth - insets.right), height: 0.0) - - // Disclosure Button - var rDisclosure = CGRect.zero - rDisclosure.size = MainFeedTableViewSectionHeaderLayout.disclosureButtonSize - rDisclosure.origin.x = bounds.origin.x - - // Unread Count - let unreadCountSize = unreadCountView.contentSize - let unreadCountIsHidden = unreadCountView.unreadCount < 1 - - var rUnread = CGRect.zero - if !unreadCountIsHidden { - rUnread.size = unreadCountSize - rUnread.origin.x = bounds.maxX - (MainFeedTableViewSectionHeaderLayout.unreadCountMarginRight + unreadCountSize.width) - } - - // Max Unread Count - // We can't reload Section Headers so we don't let the title extend into the (probably) worse case Unread Count area. - let maxUnreadCountView = MainFeedUnreadCountView(frame: CGRect.zero) - maxUnreadCountView.unreadCount = 888 - let maxUnreadCountSize = maxUnreadCountView.contentSize - - // Title - let rLabelx = insets.left + MainFeedTableViewSectionHeaderLayout.disclosureButtonSize.width - let rLabely = UIFontMetrics.default.scaledValue(for: MainFeedTableViewSectionHeaderLayout.verticalPadding) - - var labelWidth = CGFloat.zero - labelWidth = cellWidth - (rLabelx + MainFeedTableViewSectionHeaderLayout.labelMarginRight + maxUnreadCountSize.width + MainFeedTableViewSectionHeaderLayout.unreadCountMarginRight) - - let labelSizeInfo = MultilineUILabelSizer.size(for: label.text ?? "", font: label.font, numberOfLines: 0, width: Int(floor(labelWidth))) - var rLabel = CGRect(x: rLabelx, y: rLabely, width: labelWidth, height: labelSizeInfo.size.height) - - // Determine cell height - let paddedLabelHeight = rLabel.maxY + UIFontMetrics.default.scaledValue(for: MainFeedTableViewSectionHeaderLayout.verticalPadding) - let maxGraphicsHeight = [rUnread, rDisclosure].maxY() - var cellHeight = max(paddedLabelHeight, maxGraphicsHeight) - if cellHeight < MainFeedTableViewSectionHeaderLayout.minRowHeight { - cellHeight = MainFeedTableViewSectionHeaderLayout.minRowHeight - } - - // Center in Cell - let newBounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: cellHeight) - if !unreadCountIsHidden { - rUnread = MainFeedTableViewCellLayout.centerVertically(rUnread, newBounds) - } - rDisclosure = MainFeedTableViewCellLayout.centerVertically(rDisclosure, newBounds) - - // Small fonts need centered if we hit the minimum row height - if cellHeight == MainFeedTableViewSectionHeaderLayout.minRowHeight { - rLabel = MainFeedTableViewCellLayout.centerVertically(rLabel, newBounds) - } - - // Assign the properties - self.height = cellHeight - self.unreadCountRect = rUnread - self.disclosureButtonRect = rDisclosure - self.titleRect = rLabel - - } - -} diff --git a/iOS/MainFeed/Cell/MainFeedUnreadCountView.swift b/iOS/MainFeed/Cell/MainFeedUnreadCountView.swift deleted file mode 100644 index 9f2919343..000000000 --- a/iOS/MainFeed/Cell/MainFeedUnreadCountView.swift +++ /dev/null @@ -1,123 +0,0 @@ -// -// MainFeedUnreadCountView.swift -// NetNewsWire -// -// Created by Brent Simmons on 11/22/15. -// Copyright © 2015 Ranchero Software, LLC. All rights reserved. -// - -import UIKit - -class MainFeedUnreadCountView : UIView { - - var padding: UIEdgeInsets { - return UIEdgeInsets(top: 1.0, left: 9.0, bottom: 1.0, right: 9.0) - } - - let cornerRadius = 8.0 - let bgColor = AppAssets.controlBackgroundColor - var textColor: UIColor { - return UIColor.white - } - - var textAttributes: [NSAttributedString.Key: AnyObject] { - let textFont = UIFont.preferredFont(forTextStyle: .caption1).bold() - return [NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.font: textFont, NSAttributedString.Key.kern: NSNull()] - } - var textSizeCache = [Int: CGSize]() - - var unreadCount = 0 { - didSet { - contentSizeIsValid = false - invalidateIntrinsicContentSize() - setNeedsDisplay() - } - } - - var unreadCountString: String { - return unreadCount < 1 ? "" : "\(unreadCount)" - } - - private var contentSizeIsValid = false - private var _contentSize = CGSize.zero - - override init(frame: CGRect) { - super.init(frame: frame) - self.isOpaque = false - } - - required init?(coder aDecoder: NSCoder) { - super.init(coder: aDecoder) - self.isOpaque = false - } - - override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { - textSizeCache = [Int: CGSize]() - contentSizeIsValid = false - setNeedsDisplay() - } - - var contentSize: CGSize { - if !contentSizeIsValid { - var size = CGSize.zero - if unreadCount > 0 { - size = textSize() - size.width += (padding.left + padding.right) - size.height += (padding.top + padding.bottom) - } - _contentSize = size - contentSizeIsValid = true - } - return _contentSize - } - - // Prevent autolayout from messing around with our frame settings - override var intrinsicContentSize: CGSize { - return CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric) - } - - func textSize() -> CGSize { - - if unreadCount < 1 { - return CGSize.zero - } - - if let cachedSize = textSizeCache[unreadCount] { - return cachedSize - } - - var size = unreadCountString.size(withAttributes: textAttributes) - size.height = ceil(size.height) - size.width = ceil(size.width) - - textSizeCache[unreadCount] = size - return size - - } - - func textRect() -> CGRect { - - let size = textSize() - var r = CGRect.zero - r.size = size - r.origin.x = (bounds.maxX - padding.right) - r.size.width - r.origin.y = padding.top - return r - - } - - override func draw(_ dirtyRect: CGRect) { - - let cornerRadii = CGSize(width: cornerRadius, height: cornerRadius) - let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: cornerRadii) - bgColor.setFill() - path.fill() - - if unreadCount > 0 { - unreadCountString.draw(at: textRect().origin, withAttributes: textAttributes) - } - - } - -} - diff --git a/iOS/MainFeed/Cell/MainFeedRowIdentifier.swift b/iOS/MainFeed/Collection View Cells/MainFeedRowIdentifier.swift similarity index 100% rename from iOS/MainFeed/Cell/MainFeedRowIdentifier.swift rename to iOS/MainFeed/Collection View Cells/MainFeedRowIdentifier.swift diff --git a/iOS/MainFeed/MainFeedViewController+Drag.swift b/iOS/MainFeed/MainFeedViewController+Drag.swift deleted file mode 100644 index 6c15c2ce9..000000000 --- a/iOS/MainFeed/MainFeedViewController+Drag.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// MainFeedViewController+Drag.swift -// NetNewsWire-iOS -// -// Created by Maurice Parker on 11/20/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit -import MobileCoreServices -import Account -import UniformTypeIdentifiers - -extension MainFeedViewController: UITableViewDragDelegate { - - func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { - guard let node = coordinator.nodeFor(indexPath), let webFeed = node.representedObject as? WebFeed else { - return [UIDragItem]() - } - - let data = webFeed.url.data(using: .utf8) - let itemProvider = NSItemProvider() - - itemProvider.registerDataRepresentation(forTypeIdentifier: UTType.url.identifier, visibility: .ownProcess) { completion in - completion(data, nil) - return nil - } - - let dragItem = UIDragItem(itemProvider: itemProvider) - dragItem.localObject = node - return [dragItem] - } - -} diff --git a/iOS/MainFeed/MainFeedViewController+Drop.swift b/iOS/MainFeed/MainFeedViewController+Drop.swift deleted file mode 100644 index 516c328fd..000000000 --- a/iOS/MainFeed/MainFeedViewController+Drop.swift +++ /dev/null @@ -1,166 +0,0 @@ -// -// MainFeedViewController+Drop.swift -// NetNewsWire-iOS -// -// Created by Maurice Parker on 11/20/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit -import RSCore -import Account -import RSTree - -extension MainFeedViewController: UITableViewDropDelegate { - - func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool { - return session.localDragSession != nil - } - - func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal { - guard let destIndexPath = destinationIndexPath, destIndexPath.section > 0, tableView.hasActiveDrag else { - return UITableViewDropProposal(operation: .forbidden) - } - - guard let destFeed = coordinator.nodeFor(destIndexPath)?.representedObject as? Feed, - let destAccount = destFeed.account, - let destCell = tableView.cellForRow(at: destIndexPath) else { - return UITableViewDropProposal(operation: .forbidden) - } - - // Validate account specific behaviors... - if destAccount.behaviors.contains(.disallowFeedInMultipleFolders), - let sourceNode = session.localDragSession?.items.first?.localObject as? Node, - let sourceWebFeed = sourceNode.representedObject as? WebFeed, - sourceWebFeed.account?.accountID != destAccount.accountID && destAccount.hasWebFeed(withURL: sourceWebFeed.url) { - return UITableViewDropProposal(operation: .forbidden) - } - - // Determine the correct drop proposal - if destFeed is Folder { - if session.location(in: destCell).y >= 0 { - return UITableViewDropProposal(operation: .move, intent: .insertIntoDestinationIndexPath) - } else { - return UITableViewDropProposal(operation: .move, intent: .unspecified) - } - } else { - return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath) - } - - } - - func tableView(_ tableView: UITableView, performDropWith dropCoordinator: UITableViewDropCoordinator) { - guard let dragItem = dropCoordinator.items.first?.dragItem, - let dragNode = dragItem.localObject as? Node, - let source = dragNode.parent?.representedObject as? Container, - let destIndexPath = dropCoordinator.destinationIndexPath else { - return - } - - let isFolderDrop: Bool = { - if coordinator.nodeFor(destIndexPath)?.representedObject is Folder, let propCell = tableView.cellForRow(at: destIndexPath) { - return dropCoordinator.session.location(in: propCell).y >= 0 - } - return false - }() - - // Based on the drop we have to determine a node to start looking for a parent container. - let destNode: Node? = { - - if isFolderDrop { - return coordinator.nodeFor(destIndexPath) - } else { - if destIndexPath.row == 0 { - return coordinator.nodeFor(IndexPath(row: 0, section: destIndexPath.section)) - } else if destIndexPath.row > 0 { - return coordinator.nodeFor(IndexPath(row: destIndexPath.row - 1, section: destIndexPath.section)) - } else { - return nil - } - } - - }() - - // Now we start looking for the parent container - let destinationContainer: Container? = { - if let container = (destNode?.representedObject as? Container) ?? (destNode?.parent?.representedObject as? Container) { - return container - } else { - // If we got here, we are trying to drop on an empty section header. Go and find the Account for this section - return coordinator.rootNode.childAtIndex(destIndexPath.section)?.representedObject as? Account - } - }() - - guard let destination = destinationContainer, let webFeed = dragNode.representedObject as? WebFeed else { return } - - if source.account == destination.account { - moveWebFeedInAccount(feed: webFeed, sourceContainer: source, destinationContainer: destination) - } else { - moveWebFeedBetweenAccounts(feed: webFeed, sourceContainer: source, destinationContainer: destination) - } - } - - func moveWebFeedInAccount(feed: WebFeed, sourceContainer: Container, destinationContainer: Container) { - guard sourceContainer !== destinationContainer else { return } - - BatchUpdate.shared.start() - sourceContainer.account?.moveWebFeed(feed, from: sourceContainer, to: destinationContainer) { result in - BatchUpdate.shared.end() - switch result { - case .success: - break - case .failure(let error): - self.presentError(error) - } - } - } - - func moveWebFeedBetweenAccounts(feed: WebFeed, sourceContainer: Container, destinationContainer: Container) { - - if let existingFeed = destinationContainer.account?.existingWebFeed(withURL: feed.url) { - - BatchUpdate.shared.start() - destinationContainer.account?.addWebFeed(existingFeed, to: destinationContainer) { result in - switch result { - case .success: - sourceContainer.account?.removeWebFeed(feed, from: sourceContainer) { result in - BatchUpdate.shared.end() - switch result { - case .success: - break - case .failure(let error): - self.presentError(error) - } - } - case .failure(let error): - BatchUpdate.shared.end() - self.presentError(error) - } - } - - } else { - - BatchUpdate.shared.start() - destinationContainer.account?.createWebFeed(url: feed.url, name: feed.editedName, container: destinationContainer, validateFeed: false) { result in - switch result { - case .success: - sourceContainer.account?.removeWebFeed(feed, from: sourceContainer) { result in - BatchUpdate.shared.end() - switch result { - case .success: - break - case .failure(let error): - self.presentError(error) - } - } - case .failure(let error): - BatchUpdate.shared.end() - self.presentError(error) - } - } - - } - } - - -} diff --git a/iOS/MainFeed/MainFeedViewController.swift b/iOS/MainFeed/MainFeedViewController.swift deleted file mode 100644 index eead0a72e..000000000 --- a/iOS/MainFeed/MainFeedViewController.swift +++ /dev/null @@ -1,1315 +0,0 @@ -// -// MainFeedViewController.swift -// NetNewsWire -// -// Created by Maurice Parker on 4/8/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit -import WebKit -import Account -import Articles -import RSCore -import RSTree -import RSWeb -import SafariServices - -class MainFeedViewController: UITableViewController, UndoableCommandRunner { - - @IBOutlet weak var filterButton: UIBarButtonItem! - @IBOutlet weak var addNewItemButton: UIBarButtonItem! { - didSet { - if #available(iOS 14, *) { - addNewItemButton.primaryAction = nil - } else { - addNewItemButton.action = #selector(MainFeedViewController.add(_:)) - } - } - } - - var undoableCommands = [UndoableCommand]() - weak var coordinator: SceneCoordinator! - - private let keyboardManager = KeyboardManager(type: .sidebar) - override var keyCommands: [UIKeyCommand]? { - - // If the first responder is the WKWebView (PreloadedWebView) we don't want to supply any keyboard - // commands that the system is looking for by going up the responder chain. They will interfere with - // the WKWebViews built in hardware keyboard shortcuts, specifically the up and down arrow keys. - guard let current = UIResponder.currentFirstResponder, !(current is PreloadedWebView) else { return nil } - - return keyboardManager.keyCommands - } - - override var canBecomeFirstResponder: Bool { - return true - } - - override func viewDidLoad() { - - super.viewDidLoad() - - - tableView.register(MainFeedTableViewSectionHeader.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") - tableView.dragDelegate = self - tableView.dropDelegate = self - tableView.dragInteractionEnabled = true - tableView.separatorStyle = .none - - NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .FaviconDidBecomeAvailable, object: nil) - - // TODO: fix this temporary hack, which will probably require refactoring image handling. - // We want to know when to possibly reconfigure our cells with a new image, and we don’t - // always know when an image is available — but watching the .htmlMetadataAvailable Notification - // lets us know that it’s time to request an image. - NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .htmlMetadataAvailable, object: nil) - - NotificationCenter.default.addObserver(self, selector: #selector(webFeedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(webFeedSettingDidChange(_:)), name: .WebFeedSettingDidChange, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil) - - registerForTraitChanges([UITraitPreferredContentSizeCategory.self], target: self, action: #selector(preferredContentSizeCategoryDidChange)) - - - becomeFirstResponder() - } - - override func viewWillAppear(_ animated: Bool) { - navigationController?.isToolbarHidden = false - updateUI() - super.viewWillAppear(animated) - - if traitCollection.userInterfaceIdiom == .phone { - navigationController?.navigationBar.prefersLargeTitles = true - } - resetEstimatedRowHeight() - refreshControl = UIRefreshControl() - refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged) - } - - // MARK: Notifications - - @objc func preferredContentSizeCategoryDidChange() { - IconImageCache.shared.emptyCache() - reloadAllVisibleCells() - } - - private func headerViewForAccount(_ account: Account) -> MainFeedTableViewSectionHeader? { - - guard let node = coordinator.rootNode.childNodeRepresentingObject(account), - let sectionIndex = coordinator.rootNode.indexOfChild(node) else { - return nil - } - - return tableView.headerView(forSection: sectionIndex) as? MainFeedTableViewSectionHeader - } - - @objc func unreadCountDidChange(_ note: Notification) { - updateUI() - - guard let unreadCountProvider = note.object as? UnreadCountProvider else { - return - } - - if let account = unreadCountProvider as? Account { - if let headerView = headerViewForAccount(account) { - headerView.unreadCount = account.unreadCount - } - return - } - - var node: Node? = nil - if let coordinator = unreadCountProvider as? SceneCoordinator, let feed = coordinator.timelineFeed { - node = coordinator.rootNode.descendantNodeRepresentingObject(feed as AnyObject) - } else { - node = coordinator.rootNode.descendantNodeRepresentingObject(unreadCountProvider as AnyObject) - } - - guard let unreadCountNode = node, let indexPath = coordinator.indexPathFor(unreadCountNode) else { return } - if let cell = tableView.cellForRow(at: indexPath) as? MainFeedTableViewCell { - cell.unreadCount = unreadCountProvider.unreadCount - } - } - - @objc func faviconDidBecomeAvailable(_ note: Notification) { - applyToAvailableCells(configureIcon) - } - - @objc func webFeedIconDidBecomeAvailable(_ note: Notification) { - guard let webFeed = note.userInfo?[UserInfoKey.webFeed] as? WebFeed else { - return - } - applyToCellsForRepresentedObject(webFeed, configureIcon(_:_:)) - } - - @objc func webFeedSettingDidChange(_ note: Notification) { - guard let webFeed = note.object as? WebFeed, let key = note.userInfo?[WebFeed.WebFeedSettingUserInfoKey] as? String else { - return - } - if key == WebFeed.WebFeedSettingKey.homePageURL || key == WebFeed.WebFeedSettingKey.faviconURL { - configureCellsForRepresentedObject(webFeed) - } - } - - @objc func displayNameDidChange(_ note: Notification) { - - if let account = note.object as? Account { - if let headerView = headerViewForAccount(account) { - headerView.name = account.nameForDisplay - } - return - } - - if let representedObject = note.object as? AnyObject { - configureCellsForRepresentedObject(representedObject) - } - } - - @objc func contentSizeCategoryDidChange(_ note: Notification) { - resetEstimatedRowHeight() - tableView.reloadData() - } - - @objc func willEnterForeground(_ note: Notification) { - updateUI() - } - - // MARK: Table View - - override func numberOfSections(in tableView: UITableView) -> Int { - coordinator.numberOfSections() - } - - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - coordinator.numberOfRows(in: section) - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MainFeedTableViewCell - configure(cell, indexPath) - return cell - } - - override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { - if coordinator.nodeFor(indexPath)?.representedObject is PseudoFeed { - return false - } else { - return true - } - } - - override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { - - guard let nameProvider = coordinator.rootNode.childAtIndex(section)?.representedObject as? DisplayNameProvider else { - return 44 - } - - let headerView = MainFeedTableViewSectionHeader() - headerView.name = nameProvider.nameForDisplay - - let size = headerView.sizeThatFits(CGSize(width: tableView.bounds.width, height: 0.0)) - return size.height - - } - - override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { - - guard let nameProvider = coordinator.rootNode.childAtIndex(section)?.representedObject as? DisplayNameProvider else { - return nil - } - - let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! MainFeedTableViewSectionHeader - headerView.delegate = self - headerView.name = nameProvider.nameForDisplay - - guard let sectionNode = coordinator.rootNode.childAtIndex(section) else { - return headerView - } - - if let account = sectionNode.representedObject as? Account { - headerView.unreadCount = account.unreadCount - } else { - headerView.unreadCount = 0 - } - - headerView.tag = section - headerView.disclosureExpanded = coordinator.isExpanded(sectionNode) - - if section == tableView.numberOfSections - 1 { - headerView.isLastSection = true - } else { - headerView.isLastSection = false - } - - headerView.gestureRecognizers?.removeAll() - let tap = UITapGestureRecognizer(target: self, action:#selector(self.toggleSectionHeader(_:))) - headerView.addGestureRecognizer(tap) - - // Without this the swipe gesture registers on the cell below - let gestureRecognizer = UIPanGestureRecognizer(target: nil, action: nil) - gestureRecognizer.delegate = self - headerView.addGestureRecognizer(gestureRecognizer) - - headerView.interactions.removeAll() - if section != 0 { - headerView.addInteraction(UIContextMenuInteraction(delegate: self)) - } - - return headerView - - } - - override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { - return CGFloat.leastNormalMagnitude - } - - override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { - return UIView(frame: CGRect.zero) - } - - override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { - var actions = [UIContextualAction]() - - // Set up the delete action - let deleteTitle = NSLocalizedString("Delete", comment: "Delete") - let deleteAction = UIContextualAction(style: .normal, title: deleteTitle) { [weak self] (action, view, completion) in - self?.delete(indexPath: indexPath) - completion(true) - } - deleteAction.backgroundColor = UIColor.systemRed - actions.append(deleteAction) - - // Set up the rename action - let renameTitle = NSLocalizedString("Rename", comment: "Rename") - let renameAction = UIContextualAction(style: .normal, title: renameTitle) { [weak self] (action, view, completion) in - self?.rename(indexPath: indexPath) - completion(true) - } - renameAction.backgroundColor = UIColor.systemOrange - actions.append(renameAction) - - if let webFeed = coordinator.nodeFor(indexPath)?.representedObject as? WebFeed { - 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: webFeed.nameForDisplay, message: nil, preferredStyle: .actionSheet) - if let popoverController = alert.popoverPresentationController { - popoverController.sourceView = view - popoverController.sourceRect = CGRect(x: view.frame.size.width/2, y: view.frame.size.height/2, width: 1, height: 1) - } - - if let action = self.getInfoAlertAction(indexPath: indexPath, completion: completion) { - alert.addAction(action) - } - - if let action = self.homePageAlertAction(indexPath: indexPath, completion: completion) { - alert.addAction(action) - } - - if let action = self.copyFeedPageAlertAction(indexPath: indexPath, completion: completion) { - alert.addAction(action) - } - - if let action = self.copyHomePageAlertAction(indexPath: indexPath, completion: completion) { - alert.addAction(action) - } - - if let action = self.markAllAsReadAlertAction(indexPath: indexPath, completion: completion) { - alert.addAction(action) - } - - let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") - alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel) { _ in - completion(true) - }) - - self.present(alert, animated: true) - - } - - } - - moreAction.backgroundColor = UIColor.systemGray - actions.append(moreAction) - } - - return UISwipeActionsConfiguration(actions: actions) - - } - - override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { - guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed else { - return nil - } - if feed is WebFeed { - return makeWebFeedContextMenu(indexPath: indexPath, includeDeleteRename: true) - } else if feed is Folder { - return makeFolderContextMenu(indexPath: indexPath) - } else if feed is PseudoFeed { - return makePseudoFeedContextMenu(indexPath: indexPath) - } else { - return nil - } - } - - override func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { - guard let identifier = configuration.identifier as? MainFeedRowIdentifier, - let cell = tableView.cellForRow(at: identifier.indexPath) else { - return nil - } - - return UITargetedPreview(view: cell, parameters: CroppingPreviewParameters(view: cell)) - } - - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - becomeFirstResponder() - coordinator.selectFeed(indexPath: indexPath, animations: [.navigation, .select, .scroll]) - } - - override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { - - // Adjust the index path so that it will never be in the smart feeds area - let destIndexPath: IndexPath = { - if proposedDestinationIndexPath.section == 0 { - return IndexPath(row: 0, section: 1) - } - return coordinator.cappedIndexPath(proposedDestinationIndexPath) - }() - - guard let draggedNode = coordinator.nodeFor(sourceIndexPath) else { - assertionFailure("This should never happen") - return sourceIndexPath - } - - // If there is no destination node, we are dragging onto an empty Account - guard let destNode = coordinator.nodeFor(destIndexPath), - let destParentNode = destNode.parent else { - return proposedDestinationIndexPath - } - - // If this is a folder, let the users drop on it - if destNode.representedObject is Folder { - return proposedDestinationIndexPath - } - - // If we are dragging around in the same container, just return the original source - if destParentNode.childNodes.contains(draggedNode) { - return sourceIndexPath - } - - // Suggest to the user the best place to drop the feed - // Revisit if the tree controller can ever be sorted in some other way. - let nodes = destParentNode.childNodes + [draggedNode] - var sortedNodes = nodes.sortedAlphabeticallyWithFoldersAtEnd() - let index = sortedNodes.firstIndex(of: draggedNode)! - - sortedNodes.remove(at: index) - - if index == 0 { - - if destParentNode.representedObject is Account { - return IndexPath(row: 0, section: destIndexPath.section) - } else { - if let candidateIndexPath = coordinator.indexPathFor(sortedNodes[index]) { - let movementAdjustment = sourceIndexPath < destIndexPath ? 1 : 0 - return IndexPath(row: candidateIndexPath.row - movementAdjustment, section: candidateIndexPath.section) - } else { - return sourceIndexPath - } - } - - } else { - - if index >= sortedNodes.count { - if let lastSortedIndexPath = coordinator.indexPathFor(sortedNodes[sortedNodes.count - 1]) { - let movementAdjustment = sourceIndexPath > destIndexPath ? 1 : 0 - return IndexPath(row: lastSortedIndexPath.row + movementAdjustment, section: lastSortedIndexPath.section) - } else { - return sourceIndexPath - } - } else { - let movementAdjustment = sourceIndexPath < destIndexPath ? 1 : 0 - return coordinator.indexPathFor(sortedNodes[index - movementAdjustment]) ?? sourceIndexPath - } - - } - - } - - // MARK: Actions - - @IBAction func settings(_ sender: UIBarButtonItem) { - coordinator.showSettings() - } - - @IBAction func toggleFilter(_ sender: Any) { - coordinator.toggleReadFeedsFilter() - } - - @IBAction func add(_ sender: UIBarButtonItem) { - - if #available(iOS 14, *) { - - } else { - let title = NSLocalizedString("Add Item", comment: "Add Item") - let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) - - let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") - let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) - - let addWebFeedActionTitle = NSLocalizedString("Add Web Feed", comment: "Add Web Feed") - let addWebFeedAction = UIAlertAction(title: addWebFeedActionTitle, style: .default) { _ in - self.coordinator.showAddWebFeed() - } - - let addWebFolderdActionTitle = NSLocalizedString("Add Folder", comment: "Add Folder") - let addWebFolderAction = UIAlertAction(title: addWebFolderdActionTitle, style: .default) { _ in - self.coordinator.showAddFolder() - } - - alertController.addAction(addWebFeedAction) - - alertController.addAction(addWebFolderAction) - alertController.addAction(cancelAction) - - alertController.popoverPresentationController?.barButtonItem = sender - - present(alertController, animated: true) - } - - - } - - @objc func toggleSectionHeader(_ sender: UITapGestureRecognizer) { - guard let headerView = sender.view as? MainFeedTableViewSectionHeader else { - return - } - toggle(headerView) - } - - @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?) { - coordinator.selectPrevFeed() - } - - @objc func selectNextDown(_ sender: Any?) { - coordinator.selectNextFeed() - } - - @objc func navigateToTimeline(_ sender: Any?) { - coordinator.navigateToTimeline() - } - - @objc func openInBrowser(_ sender: Any?) { - coordinator.showBrowserForCurrentFeed() - } - - @objc override func delete(_ sender: Any?) { - if let indexPath = coordinator.currentFeedIndexPath { - delete(indexPath: indexPath) - } - } - - override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { - if action == #selector(UIResponder.delete(_:)) { - return isFirstResponder - } - return super.canPerformAction(action, withSender: sender) - } - - @objc func expandSelectedRows(_ sender: Any?) { - if let indexPath = coordinator.currentFeedIndexPath, let node = coordinator.nodeFor(indexPath) { - coordinator.expand(node) - } - } - - @objc func collapseSelectedRows(_ sender: Any?) { - if let indexPath = coordinator.currentFeedIndexPath, let node = coordinator.nodeFor(indexPath) { - coordinator.collapse(node) - } - } - - @objc func expandAll(_ sender: Any?) { - coordinator.expandAllSectionsAndFolders() - } - - @objc func collapseAllExceptForGroupItems(_ sender: Any?) { - coordinator.collapseAllFolders() - } - - @objc func markAllAsRead(_ sender: Any) { - guard let indexPath = tableView.indexPathForSelectedRow, let contentView = tableView.cellForRow(at: indexPath)?.contentView else { - return - } - - let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read") - MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in - self?.coordinator.markAllAsReadInTimeline() - } - } - - @objc func showFeedInspector(_ sender: Any?) { - coordinator.showFeedInspector() - } - - // MARK: API - - func restoreSelectionIfNecessary(adjustScroll: Bool) { - if let indexPath = coordinator.mainFeedIndexPathForCurrentTimeline() { - if adjustScroll { - tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: []) - } else { - tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) - } - } - } - - func updateFeedSelection(animations: Animations) { - if let indexPath = coordinator.currentFeedIndexPath { - tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: animations) - } else { - if let indexPath = tableView.indexPathForSelectedRow { - if animations.contains(.select) { - tableView.deselectRow(at: indexPath, animated: true) - } else { - tableView.deselectRow(at: indexPath, animated: false) - } - } - } - } - - func reloadFeeds(initialLoad: Bool, changes: ShadowTableChanges, completion: (() -> Void)? = nil) { - updateUI() - - guard !initialLoad else { - tableView.reloadData() - completion?() - return - } - - tableView.performBatchUpdates { - if let deletes = changes.deletes, !deletes.isEmpty { - tableView.deleteSections(IndexSet(deletes), with: .middle) - } - - if let inserts = changes.inserts, !inserts.isEmpty { - tableView.insertSections(IndexSet(inserts), with: .middle) - } - - if let moves = changes.moves, !moves.isEmpty { - for move in moves { - tableView.moveSection(move.from, toSection: move.to) - } - } - - if let rowChanges = changes.rowChanges { - for rowChange in rowChanges { - if let deletes = rowChange.deleteIndexPaths, !deletes.isEmpty { - tableView.deleteRows(at: deletes, with: .middle) - } - - if let inserts = rowChange.insertIndexPaths, !inserts.isEmpty { - tableView.insertRows(at: inserts, with: .middle) - } - - if let moves = rowChange.moveIndexPaths, !moves.isEmpty { - for move in moves { - tableView.moveRow(at: move.0, to: move.1) - } - } - } - } - } - - if let rowChanges = changes.rowChanges { - for rowChange in rowChanges { - if let reloads = rowChange.reloadIndexPaths, !reloads.isEmpty { - tableView.reloadRows(at: reloads, with: .none) - } - } - } - - completion?() - } - - func updateUI() { - if coordinator.isReadFeedsFiltered { - setFilterButtonToActive() - } else { - setFilterButtonToInactive() - } - addNewItemButton?.isEnabled = !AccountManager.shared.activeAccounts.isEmpty - - configureContextMenu() - } - - @objc - func configureContextMenu(_: Any? = nil) { - if #available(iOS 14.0, *) { - - /* - Context Menu Order: - 1. Add Web Feed - 2. Add Folder - */ - - var menuItems: [UIAction] = [] - - let addWebFeedActionTitle = NSLocalizedString("Add Feed", comment: "Add Feed") - let addWebFeedAction = UIAction(title: addWebFeedActionTitle, image: AppAssets.plus) { _ in - self.coordinator.showAddWebFeed() - } - menuItems.append(addWebFeedAction) - - let addWebFolderActionTitle = NSLocalizedString("Add Folder", comment: "Add Folder") - let addWebFolderAction = UIAction(title: addWebFolderActionTitle, image: AppAssets.folderOutlinePlus) { _ in - self.coordinator.showAddFolder() - } - - menuItems.append(addWebFolderAction) - - let contextMenu = UIMenu(title: NSLocalizedString("Add Item", comment: "Add Item"), image: nil, identifier: nil, options: [], children: menuItems.reversed()) - - self.addNewItemButton.menu = contextMenu - } - } - - - - func focus() { - becomeFirstResponder() - } - - func openInAppBrowser() { - if let indexPath = coordinator.currentFeedIndexPath, - let url = coordinator.homePageURLForFeed(indexPath) { - let vc = SFSafariViewController(url: url) - vc.modalPresentationStyle = .overFullScreen - present(vc, animated: true) - } - } - -} - -// MARK: UIContextMenuInteractionDelegate - -extension MainFeedViewController: UIContextMenuInteractionDelegate { - func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { - - guard let sectionIndex = interaction.view?.tag, - let sectionNode = coordinator.rootNode.childAtIndex(sectionIndex), - let account = sectionNode.representedObject as? Account - else { - return nil - } - - return UIContextMenuConfiguration(identifier: sectionIndex as NSCopying, previewProvider: nil) { suggestedActions in - - var menuElements = [UIMenuElement]() - menuElements.append(UIMenu(title: "", options: .displayInline, children: [self.getAccountInfoAction(account: account)])) - - if let markAllAction = self.markAllAsReadAction(account: account, contentView: interaction.view) { - menuElements.append(UIMenu(title: "", options: .displayInline, children: [markAllAction])) - } - - menuElements.append(UIMenu(title: "", options: .displayInline, children: [self.deactivateAccountAction(account: account)])) - - return UIMenu(title: "", children: menuElements) - } - } - - func contextMenuInteraction(_ interaction: UIContextMenuInteraction, previewForHighlightingMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { - - guard let sectionIndex = configuration.identifier as? Int, - let cell = tableView.headerView(forSection: sectionIndex) else { - return nil - } - - return UITargetedPreview(view: cell, parameters: CroppingPreviewParameters(view: cell)) - } -} - -// MARK: MainFeedTableViewSectionHeaderDelegate - -extension MainFeedViewController: MainFeedTableViewSectionHeaderDelegate { - - func mainFeedTableViewSectionHeaderDisclosureDidToggle(_ sender: MainFeedTableViewSectionHeader) { - toggle(sender) - } - -} - -// MARK: MainTableViewCellDelegate - -extension MainFeedViewController: MainFeedTableViewCellDelegate { - - func mainFeedTableViewCellDisclosureDidToggle(_ sender: MainFeedTableViewCell, expanding: Bool) { - if expanding { - expand(sender) - } else { - collapse(sender) - } - } - -} - -// MARK: Private - -private extension MainFeedViewController { - - func setFilterButtonToActive() { - filterButton.style = .prominent - filterButton.tintColor = AppAssets.primaryAccentColor - filterButton?.accLabelText = NSLocalizedString("Selected - Filter Read Feeds", comment: "Selected - Filter Read Feeds") - } - - func setFilterButtonToInactive() { - filterButton.style = .plain - filterButton.tintColor = nil - filterButton?.accLabelText = NSLocalizedString("Filter Read Feeds", comment: "Filter Read Feeds") - } - - func resetEstimatedRowHeight() { - let titleLabel = NonIntrinsicLabel() - titleLabel.text = "But I must explain" - - let unreadCountView = MainFeedUnreadCountView() - unreadCountView.unreadCount = 10 - - let layout = MainFeedTableViewCellLayout(cellWidth: tableView.bounds.size.width, insets: tableView.safeAreaInsets, label: titleLabel, unreadCountView: unreadCountView, showingEditingControl: false, indent: false, shouldShowDisclosure: false) - tableView.estimatedRowHeight = layout.height - } - - func configure(_ cell: MainFeedTableViewCell, _ indexPath: IndexPath) { - guard let node = coordinator.nodeFor(indexPath) else { return } - - cell.delegate = self - if node.representedObject is Folder { - cell.indentationLevel = 0 - } else { - cell.indentationLevel = 1 - } - - if let containerID = (node.representedObject as? Container)?.containerID { - cell.setDisclosure(isExpanded: coordinator.isExpanded(containerID), animated: false) - cell.isDisclosureAvailable = true - } else { - cell.isDisclosureAvailable = false - } - - if let feed = node.representedObject as? Feed { - cell.name = feed.nameForDisplay - cell.unreadCount = feed.unreadCount - } - - configureIcon(cell, indexPath) - - let rowsInSection = tableView.numberOfRows(inSection: indexPath.section) - if indexPath.row == rowsInSection - 1 { - cell.isSeparatorShown = false - } else { - cell.isSeparatorShown = true - } - - } - - func configureIcon(_ cell: MainFeedTableViewCell, _ indexPath: IndexPath) { - guard let node = coordinator.nodeFor(indexPath), let feed = node.representedObject as? Feed, let feedID = feed.feedID else { - return - } - cell.iconImage = IconImageCache.shared.imageFor(feedID) - } - - func nameFor(_ node: Node) -> String { - if let displayNameProvider = node.representedObject as? DisplayNameProvider { - return displayNameProvider.nameForDisplay - } - return "" - } - - func configureCellsForRepresentedObject(_ representedObject: AnyObject) { - applyToCellsForRepresentedObject(representedObject, configure) - } - - func applyToCellsForRepresentedObject(_ representedObject: AnyObject, _ completion: (MainFeedTableViewCell, IndexPath) -> Void) { - applyToAvailableCells { (cell, indexPath) in - if let node = coordinator.nodeFor(indexPath), - let representedFeed = representedObject as? Feed, - let candidate = node.representedObject as? Feed, - representedFeed.feedID == candidate.feedID { - completion(cell, indexPath) - } - } - } - - func applyToAvailableCells(_ completion: (MainFeedTableViewCell, IndexPath) -> Void) { - tableView.visibleCells.forEach { cell in - guard let indexPath = tableView.indexPath(for: cell) else { - return - } - completion(cell as! MainFeedTableViewCell, indexPath) - } - } - - private func reloadAllVisibleCells(completion: (() -> Void)? = nil) { - guard let indexPaths = tableView.indexPathsForVisibleRows else { return } - tableView.reloadRows(at: indexPaths, with: .none) - restoreSelectionIfNecessary(adjustScroll: false) - } - - private func accountForNode(_ node: Node) -> Account? { - if let account = node.representedObject as? Account { - return account - } - if let folder = node.representedObject as? Folder { - return folder.account - } - if let feed = node.representedObject as? WebFeed { - return feed.account - } - return nil - } - - func toggle(_ headerView: MainFeedTableViewSectionHeader) { - guard let sectionNode = coordinator.rootNode.childAtIndex(headerView.tag) else { - return - } - - if coordinator.isExpanded(sectionNode) { - headerView.disclosureExpanded = false - coordinator.collapse(sectionNode) - } else { - headerView.disclosureExpanded = true - coordinator.expand(sectionNode) - } - } - - func expand(_ cell: MainFeedTableViewCell) { - guard let indexPath = tableView.indexPath(for: cell), let node = coordinator.nodeFor(indexPath) else { - return - } - coordinator.expand(node) - } - - func collapse(_ cell: MainFeedTableViewCell) { - guard let indexPath = tableView.indexPath(for: cell), let node = coordinator.nodeFor(indexPath) else { - return - } - coordinator.collapse(node) - } - - func makeWebFeedContextMenu(indexPath: IndexPath, includeDeleteRename: Bool) -> UIContextMenuConfiguration { - return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [ weak self] suggestedActions in - - guard let self = self else { return nil } - - var menuElements = [UIMenuElement]() - - if let inspectorAction = self.getInfoAction(indexPath: indexPath) { - menuElements.append(UIMenu(title: "", options: .displayInline, children: [inspectorAction])) - } - - if let homePageAction = self.homePageAction(indexPath: indexPath) { - menuElements.append(UIMenu(title: "", options: .displayInline, children: [homePageAction])) - } - - var pageActions = [UIAction]() - if let copyFeedPageAction = self.copyFeedPageAction(indexPath: indexPath) { - pageActions.append(copyFeedPageAction) - } - if let copyHomePageAction = self.copyHomePageAction(indexPath: indexPath) { - pageActions.append(copyHomePageAction) - } - if !pageActions.isEmpty { - menuElements.append(UIMenu(title: "", options: .displayInline, children: pageActions)) - } - - if let markAllAction = self.markAllAsReadAction(indexPath: indexPath) { - menuElements.append(UIMenu(title: "", options: .displayInline, children: [markAllAction])) - } - - if includeDeleteRename { - menuElements.append(UIMenu(title: "", - options: .displayInline, - children: [ - self.renameAction(indexPath: indexPath), - self.deleteAction(indexPath: indexPath) - ])) - } - - return UIMenu(title: "", children: menuElements) - - }) - - } - - func makeFolderContextMenu(indexPath: IndexPath) -> UIContextMenuConfiguration { - return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { [weak self] suggestedActions in - - guard let self = self else { return nil } - - var menuElements = [UIMenuElement]() - - if let markAllAction = self.markAllAsReadAction(indexPath: indexPath) { - menuElements.append(UIMenu(title: "", options: .displayInline, children: [markAllAction])) - } - - menuElements.append(UIMenu(title: "", - options: .displayInline, - children: [ - self.renameAction(indexPath: indexPath), - self.deleteAction(indexPath: indexPath) - ])) - - return UIMenu(title: "", children: menuElements) - - }) - } - - func makePseudoFeedContextMenu(indexPath: IndexPath) -> UIContextMenuConfiguration? { - guard let markAllAction = self.markAllAsReadAction(indexPath: indexPath) else { - return nil - } - - return UIContextMenuConfiguration(identifier: MainFeedRowIdentifier(indexPath: indexPath), previewProvider: nil, actionProvider: { suggestedActions in - return UIMenu(title: "", children: [markAllAction]) - }) - } - - func homePageAction(indexPath: IndexPath) -> UIAction? { - guard coordinator.homePageURLForFeed(indexPath) != nil else { - return nil - } - - let title = NSLocalizedString("Open Home Page", comment: "Open Home Page") - let action = UIAction(title: title, image: AppAssets.safariImage) { [weak self] action in - self?.coordinator.showBrowserForFeed(indexPath) - } - return action - } - - func homePageAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { - guard coordinator.homePageURLForFeed(indexPath) != nil else { - return nil - } - - let title = NSLocalizedString("Open Home Page", comment: "Open Home Page") - let action = UIAlertAction(title: title, style: .default) { [weak self] action in - self?.coordinator.showBrowserForFeed(indexPath) - completion(true) - } - return action - } - - func copyFeedPageAction(indexPath: IndexPath) -> UIAction? { - guard let webFeed = coordinator.nodeFor(indexPath)?.representedObject as? WebFeed, - let url = URL(string: webFeed.url) else { - return nil - } - - let title = NSLocalizedString("Copy Feed URL", comment: "Copy Feed URL") - let action = UIAction(title: title, image: AppAssets.copyImage) { action in - UIPasteboard.general.url = url - } - return action - } - - func copyFeedPageAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { - guard let webFeed = coordinator.nodeFor(indexPath)?.representedObject as? WebFeed, - let url = URL(string: webFeed.url) else { - return nil - } - - let title = NSLocalizedString("Copy Feed URL", comment: "Copy Feed URL") - let action = UIAlertAction(title: title, style: .default) { action in - UIPasteboard.general.url = url - completion(true) - } - return action - } - - func copyHomePageAction(indexPath: IndexPath) -> UIAction? { - guard let webFeed = coordinator.nodeFor(indexPath)?.representedObject as? WebFeed, - let homePageURL = webFeed.homePageURL, - let url = URL(string: homePageURL) else { - return nil - } - - let title = NSLocalizedString("Copy Home Page URL", comment: "Copy Home Page URL") - let action = UIAction(title: title, image: AppAssets.copyImage) { action in - UIPasteboard.general.url = url - } - return action - } - - func copyHomePageAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { - guard let webFeed = coordinator.nodeFor(indexPath)?.representedObject as? WebFeed, - let homePageURL = webFeed.homePageURL, - let url = URL(string: homePageURL) else { - return nil - } - - let title = NSLocalizedString("Copy Home Page URL", comment: "Copy Home Page URL") - let action = UIAlertAction(title: title, style: .default) { action in - UIPasteboard.general.url = url - completion(true) - } - return action - } - - func markAllAsReadAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { - guard let webFeed = coordinator.nodeFor(indexPath)?.representedObject as? WebFeed, - webFeed.unreadCount > 0, - let articles = try? webFeed.fetchArticles(), 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, webFeed.nameForDisplay) as String - let cancel = { - completion(true) - } - - - let action = UIAlertAction(title: title, style: .default) { [weak self] action in - MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in - self?.coordinator.markAllAsRead(Array(articles)) - completion(true) - } - } - return action - } - - func deleteAction(indexPath: IndexPath) -> UIAction { - let title = NSLocalizedString("Delete", comment: "Delete") - - let action = UIAction(title: title, image: AppAssets.trashImage, attributes: .destructive) { [weak self] action in - self?.delete(indexPath: indexPath) - } - return action - } - - func renameAction(indexPath: IndexPath) -> UIAction { - let title = NSLocalizedString("Rename", comment: "Rename") - let action = UIAction(title: title, image: AppAssets.editImage) { [weak self] action in - self?.rename(indexPath: indexPath) - } - return action - } - - func getInfoAction(indexPath: IndexPath) -> UIAction? { - guard let webFeed = coordinator.nodeFor(indexPath)?.representedObject as? WebFeed else { - return nil - } - - let title = NSLocalizedString("Get Info", comment: "Get Info") - let action = UIAction(title: title, image: AppAssets.infoImage) { [weak self] action in - self?.coordinator.showFeedInspector(for: webFeed) - } - return action - } - - func getAccountInfoAction(account: Account) -> UIAction { - let title = NSLocalizedString("Get Info", comment: "Get Info") - let action = UIAction(title: title, image: AppAssets.infoImage) { [weak self] action in - self?.coordinator.showAccountInspector(for: account) - } - return action - } - - func deactivateAccountAction(account: Account) -> UIAction { - let title = NSLocalizedString("Deactivate", comment: "Deactivate") - let action = UIAction(title: title, image: AppAssets.deactivateImage) { action in - account.isActive = false - } - return action - } - - func getInfoAlertAction(indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? { - guard let webFeed = coordinator.nodeFor(indexPath)?.representedObject as? WebFeed else { - return nil - } - - let title = NSLocalizedString("Get Info", comment: "Get Info") - let action = UIAlertAction(title: title, style: .default) { [weak self] action in - self?.coordinator.showFeedInspector(for: webFeed) - completion(true) - } - return action - } - - func markAllAsReadAction(indexPath: IndexPath) -> UIAction? { - guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed, - let contentView = self.tableView.cellForRow(at: indexPath)?.contentView, - feed.unreadCount > 0 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: AppAssets.markAllAsReadImage) { [weak self] action in - MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in - if let articles = try? feed.fetchUnreadArticles() { - self?.coordinator.markAllAsRead(Array(articles)) - } - } - } - - return action - } - - func markAllAsReadAction(account: Account, contentView: UIView?) -> UIAction? { - guard account.unreadCount > 0, let contentView = contentView else { - return nil - } - - let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command") - let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, account.nameForDisplay) as String - let action = UIAction(title: title, image: AppAssets.markAllAsReadImage) { [weak self] action in - MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in - // If you don't have this delay the screen flashes when it executes this code - DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { - if let articles = try? account.fetchArticles(.unread()) { - self?.coordinator.markAllAsRead(Array(articles)) - } - } - } - } - - return action - } - - - func rename(indexPath: IndexPath) { - guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed else { return } - - let formatString = NSLocalizedString("Rename “%@”", comment: "Rename feed") - let title = NSString.localizedStringWithFormat(formatString as NSString, feed.nameForDisplay) as String - - let alertController = UIAlertController(title: title, message: nil, preferredStyle: .alert) - - let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") - alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel)) - - let renameTitle = NSLocalizedString("Rename", comment: "Rename") - let renameAction = UIAlertAction(title: renameTitle, style: .default) { [weak self] action in - - guard let name = alertController.textFields?[0].text, !name.isEmpty else { - return - } - - if let webFeed = feed as? WebFeed { - webFeed.rename(to: name) { result in - switch result { - case .success: - break - case .failure(let error): - self?.presentError(error) - } - } - } else if let folder = feed as? Folder { - folder.rename(to: name) { result in - switch result { - case .success: - break - case .failure(let error): - self?.presentError(error) - } - } - } - - } - - alertController.addAction(renameAction) - alertController.preferredAction = renameAction - - alertController.addTextField() { textField in - textField.text = feed.nameForDisplay - textField.placeholder = NSLocalizedString("Name", comment: "Name") - } - - self.present(alertController, animated: true) { - - } - - } - - func delete(indexPath: IndexPath) { - guard let feed = coordinator.nodeFor(indexPath)?.representedObject as? Feed else { return } - - let title: String - let message: String - if feed is Folder { - title = NSLocalizedString("Delete Folder", comment: "Delete folder") - let localizedInformativeText = NSLocalizedString("Are you sure you want to delete the “%@” folder?", comment: "Folder delete text") - message = NSString.localizedStringWithFormat(localizedInformativeText as NSString, feed.nameForDisplay) as String - } else { - title = NSLocalizedString("Delete Feed", comment: "Delete feed") - let localizedInformativeText = NSLocalizedString("Are you sure you want to delete the “%@” feed?", comment: "Feed delete text") - message = NSString.localizedStringWithFormat(localizedInformativeText as NSString, feed.nameForDisplay) as String - } - - let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) - - let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") - alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel)) - - let deleteTitle = NSLocalizedString("Delete", comment: "Delete") - let deleteAction = UIAlertAction(title: deleteTitle, style: .destructive) { [weak self] action in - self?.performDelete(indexPath: indexPath) - } - alertController.addAction(deleteAction) - alertController.preferredAction = deleteAction - - self.present(alertController, animated: true) - } - - func performDelete(indexPath: IndexPath) { - guard let undoManager = undoManager, - let deleteNode = coordinator.nodeFor(indexPath), - let deleteCommand = DeleteCommand(nodesToDelete: [deleteNode], undoManager: undoManager, errorHandler: ErrorHandler.present(self)) else { - return - } - - if let folder = deleteNode.representedObject as? Folder { - ActivityManager.cleanUp(folder) - } else if let feed = deleteNode.representedObject as? WebFeed { - ActivityManager.cleanUp(feed) - } - - if indexPath == coordinator.currentFeedIndexPath { - coordinator.selectFeed(indexPath: nil) - } - - pushUndoableCommand(deleteCommand) - deleteCommand.perform() - } - -} - -extension MainFeedViewController: UIGestureRecognizerDelegate { - func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { - guard let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer else { - return false - } - let velocity = gestureRecognizer.velocity(in: self.view) - return abs(velocity.x) > abs(velocity.y); - } -} diff --git a/iOS/MainTimeline/MainTimelineTitleView.swift b/iOS/MainTimeline/MainTimelineTitleView.swift deleted file mode 100644 index 3c4ca49df..000000000 --- a/iOS/MainTimeline/MainTimelineTitleView.swift +++ /dev/null @@ -1,64 +0,0 @@ -// -// MainTimelineTitleView.swift -// NetNewsWire-iOS -// -// Created by Maurice Parker on 9/21/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit - -class MainTimelineTitleView: UIView { - - @IBOutlet var iconView: IconView? - @IBOutlet var label: UILabel? - @IBOutlet var unreadCountView: MainTimelineUnreadCountView? - - @available(iOS 13.4, *) - private lazy var pointerInteraction: UIPointerInteraction = { - UIPointerInteraction(delegate: self) - }() - - override var accessibilityLabel: String? { - set { } - get { - if let name = label?.text { - let unreadLabel = NSLocalizedString("unread", comment: "Unread label for accessibility") - return "\(name) \(unreadCountView?.unreadCount ?? 0) \(unreadLabel)" - } - else { - return nil - } - } - } - - func buttonize() { - heightAnchor.constraint(equalToConstant: 25.0).isActive = true - accessibilityTraits = .button - if #available(iOS 13.4, *) { - addInteraction(pointerInteraction) - } - } - - func debuttonize() { - heightAnchor.constraint(equalToConstant: 25.0).isActive = true - accessibilityTraits.remove(.button) - if #available(iOS 13.4, *) { - removeInteraction(pointerInteraction) - } - } - -} - -extension MainTimelineTitleView: UIPointerInteractionDelegate { - - @available(iOS 13.4, *) - func pointerInteraction(_ interaction: UIPointerInteraction, styleFor region: UIPointerRegion) -> UIPointerStyle? { - var rect = self.frame - rect.origin.x = rect.origin.x - 10 - rect.size.width = rect.width + 20 - - return UIPointerStyle(effect: .automatic(UITargetedPreview(view: self)), shape: .roundedRect(rect)) - } - -} diff --git a/iOS/MainTimeline/MainTimelineTitleView.xib b/iOS/MainTimeline/MainTimelineTitleView.xib deleted file mode 100644 index 80ab3c45d..000000000 --- a/iOS/MainTimeline/MainTimelineTitleView.xib +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/iOS/MainTimeline/MainTimelineUnreadCountView.swift b/iOS/MainTimeline/MainTimelineUnreadCountView.swift deleted file mode 100644 index 6a0f99e3b..000000000 --- a/iOS/MainTimeline/MainTimelineUnreadCountView.swift +++ /dev/null @@ -1,39 +0,0 @@ -// -// MainTimelineUnreadCountView.swift -// NetNewsWire-iOS -// -// Created by Maurice Parker on 9/30/19. -// Copyright © 2019 Ranchero Software. All rights reserved. -// - -import UIKit - -class MainTimelineUnreadCountView: MainFeedUnreadCountView { - - override var padding: UIEdgeInsets { - return UIEdgeInsets(top: 2.0, left: 9.0, bottom: 2.0, right: 9.0) - } - - override var textColor: UIColor { - return UIColor.systemBackground - } - - override var intrinsicContentSize: CGSize { - return contentSize - } - - override func draw(_ dirtyRect: CGRect) { - - let cornerRadii = CGSize(width: cornerRadius, height: cornerRadius) - let rect = CGRect(x: 1, y: 1, width: bounds.width - 2, height: bounds.height - 2) - let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: cornerRadii) - AppAssets.primaryAccentColor.setFill() - path.fill() - - if unreadCount > 0 { - unreadCountString.draw(at: textRect().origin, withAttributes: textAttributes) - } - - } - -} diff --git a/iOS/MainTimeline/MainTimelineViewController.swift b/iOS/MainTimeline/MainTimelineViewController.swift index e646f8576..8369d8f00 100644 --- a/iOS/MainTimeline/MainTimelineViewController.swift +++ b/iOS/MainTimeline/MainTimelineViewController.swift @@ -327,7 +327,6 @@ class MainTimelineViewController: UITableViewController, UndoableCommandRunner { func updateUI() { refreshProgressView?.update() - updateTitleUnreadCount() updateToolbar() } @@ -549,11 +548,7 @@ class MainTimelineViewController: UITableViewController, UndoableCommandRunner { } @objc func webFeedIconDidBecomeAvailable(_ note: Notification) { - - if let titleView = navigationItem.titleView as? MainTimelineTitleView { - titleView.iconView?.iconImage = timelineIconImage - } - + guard let feed = note.userInfo?[UserInfoKey.webFeed] as? WebFeed else { return } @@ -586,9 +581,6 @@ class MainTimelineViewController: UITableViewController, UndoableCommandRunner { } @objc func faviconDidBecomeAvailable(_ note: Notification) { - if let titleView = navigationItem.titleView as? MainTimelineTitleView { - titleView.iconView?.iconImage = timelineIconImage - } if showIcons { queueReloadAvailableCells() } @@ -611,9 +603,7 @@ class MainTimelineViewController: UITableViewController, UndoableCommandRunner { } @objc func displayNameDidChange(_ note: Notification) { - if let titleView = navigationItem.titleView as? MainTimelineTitleView { - titleView.label?.text = timelineFeed?.nameForDisplay - } + navigationItem.title = timelineFeed?.nameForDisplay } @objc func willEnterForeground(_ note: Notification) { @@ -764,12 +754,6 @@ private extension MainTimelineViewController { } } - func updateTitleUnreadCount() { - if let titleView = navigationItem.titleView as? MainTimelineTitleView { - titleView.unreadCountView?.unreadCount = coordinator?.timelineUnreadCount ?? 0 - } - } - func applyChanges(animated: Bool, completion: (() -> Void)? = nil) { if (articles?.count ?? 0) == 0 { tableView.rowHeight = tableView.estimatedRowHeight