Clean whitespace-only lines.

This commit is contained in:
Brent Simmons committed 2025-11-05 11:22:10 -08:00
1 parent 9827300a9a
commit 9efde554d4
452 files changed
+5354 -5354

No files matched your search

@@ -18,10 +18,10 @@ final class CloudKitAccountViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupFooter()
tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader")
}
private func setupFooter() {
footerLabel.text = NSLocalizedString("NetNewsWire will use your iCloud account to sync your subscriptions across your Mac and iOS devices.", comment: "iCloud")
}
@@ -30,22 +30,22 @@ final class CloudKitAccountViewController: UITableViewController {
dismiss(animated: true, completion: nil)
delegate?.dismiss()
}
@IBAction func add(_ sender: Any) {
guard AddCloudKitAccountUtilities.isiCloudDriveEnabled else {
presentError(AddCloudKitAccountError.iCloudDriveMissing)
return
}
let _ = AccountManager.shared.createAccount(type: .cloudKit)
dismiss(animated: true, completion: nil)
delegate?.dismiss()
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView
+8 -8
View File
@@ -13,7 +13,7 @@ final class LocalAccountViewController: UITableViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var footerLabel: UILabel!
weak var delegate: AddAccountDismissDelegate?
override func viewDidLoad() {
@@ -23,7 +23,7 @@ final class LocalAccountViewController: UITableViewController {
nameTextField.delegate = self
tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader")
}
private func setupFooter() {
footerLabel.text = NSLocalizedString("Local accounts do not sync your feeds across devices.", comment: "Local")
}
@@ -31,18 +31,18 @@ final class LocalAccountViewController: UITableViewController {
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func add(_ sender: Any) {
let account = AccountManager.shared.createAccount(type: .onMyMac)
account.name = nameTextField.text
dismiss(animated: true, completion: nil)
delegate?.dismiss()
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView
@@ -52,14 +52,14 @@ final class LocalAccountViewController: UITableViewController {
return super.tableView(tableView, viewForHeaderInSection: section)
}
}
}
extension LocalAccountViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
@@ -27,7 +27,7 @@ final class ReaderAPIAccountViewController: UITableViewController {
weak var account: Account?
var accountType: AccountType?
weak var delegate: AddAccountDismissDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setupFooter()
@@ -35,7 +35,7 @@ final class ReaderAPIAccountViewController: UITableViewController {
activityIndicator.isHidden = true
usernameTextField.delegate = self
passwordTextField.delegate = self
if let unwrappedAccount = account,
let credentials = try? retrieveCredentialsForAccount(for: unwrappedAccount) {
actionButton.setTitle(NSLocalizedString("Update Credentials", comment: "Update Credentials"), for: .normal)
@@ -45,7 +45,7 @@ final class ReaderAPIAccountViewController: UITableViewController {
} else {
actionButton.setTitle(NSLocalizedString("Add Account", comment: "Add Account"), for: .normal)
}
if let unwrappedAccountType = accountType {
switch unwrappedAccountType {
case .freshRSS:
@@ -61,14 +61,14 @@ final class ReaderAPIAccountViewController: UITableViewController {
title = ""
}
}
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: usernameTextField)
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: passwordTextField)
tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader")
}
private func setupFooter() {
switch accountType {
case .bazQux:
@@ -87,11 +87,11 @@ final class ReaderAPIAccountViewController: UITableViewController {
return
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView
@@ -101,7 +101,7 @@ final class ReaderAPIAccountViewController: UITableViewController {
return super.tableView(tableView, viewForHeaderInSection: section)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
@@ -115,8 +115,8 @@ final class ReaderAPIAccountViewController: UITableViewController {
return 1
}
}
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@@ -130,19 +130,19 @@ final class ReaderAPIAccountViewController: UITableViewController {
showHideButton.setTitle("Show", for: .normal)
}
}
@IBAction func action(_ sender: Any) {
guard validateDataEntry(), let type = accountType else {
return
}
let username = usernameTextField.text!
let password = passwordTextField.text!
let url = apiURL()!
// When you fill in the email address via auto-complete it adds extra whitespace
let trimmedUsername = username.trimmingCharacters(in: .whitespaces)
guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: type, username: trimmedUsername) else {
showError(NSLocalizedString("There is already an account of that type with that username created.", comment: "Duplicate Error"))
return
@@ -196,7 +196,7 @@ final class ReaderAPIAccountViewController: UITableViewController {
}
}
}
private func retrieveCredentialsForAccount(for account: Account) throws -> Credentials? {
switch accountType {
case .bazQux, .inoreader, .theOldReader, .freshRSS:
@@ -205,7 +205,7 @@ final class ReaderAPIAccountViewController: UITableViewController {
return nil
}
}
private func headerViewImage() -> UIImage? {
if let accountType = accountType {
switch accountType {
@@ -223,7 +223,7 @@ final class ReaderAPIAccountViewController: UITableViewController {
}
return nil
}
private func validateDataEntry() -> Bool {
switch accountType {
case .freshRSS:
@@ -243,7 +243,7 @@ final class ReaderAPIAccountViewController: UITableViewController {
}
return true
}
@IBAction func signUpWithProvider(_ sender: Any) {
var url: URL!
switch accountType {
@@ -262,7 +262,7 @@ final class ReaderAPIAccountViewController: UITableViewController {
safari.modalPresentationStyle = .currentContext
self.present(safari, animated: true, completion: nil)
}
private func apiURL() -> URL? {
switch accountType {
case .freshRSS:
@@ -277,9 +277,9 @@ final class ReaderAPIAccountViewController: UITableViewController {
return nil
}
}
@objc func textDidChange(_ note: Notification) {
actionButton.isEnabled = !(usernameTextField.text?.isEmpty ?? false)
}
+3 -3
View File
@@ -12,10 +12,10 @@ final class AddComboTableViewCell: VibrantTableViewCell {
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var label: UILabel!
override func updateVibrancy(animated: Bool) {
super.updateVibrancy(animated: animated)
let iconTintColor = isHighlighted || isSelected ? AppAssets.vibrantTextColor : AppAssets.secondaryAccentColor
if animated {
UIView.animate(withDuration: Self.duration) {
@@ -26,5 +26,5 @@ final class AddComboTableViewCell: VibrantTableViewCell {
}
updateLabelVibrancy(label, color: labelColor, animated: animated)
}
}
+12 -12
View File
@@ -15,15 +15,15 @@ protocol AddFeedFolderViewControllerDelegate {
}
final class AddFeedFolderViewController: UITableViewController {
var delegate: AddFeedFolderViewControllerDelegate?
var initialContainer: Container?
var containers = [Container]()
override func viewDidLoad() {
super.viewDidLoad()
let sortedActiveAccounts = AccountManager.shared.sortedActiveAccounts
for account in sortedActiveAccounts {
@@ -53,15 +53,15 @@ final class AddFeedFolderViewController: UITableViewController {
return tableView.dequeueReusableCell(withIdentifier: "FolderCell", for: indexPath) as! AddComboTableViewCell
}
}()
if let smallIconProvider = container as? SmallIconProvider {
cell.icon?.image = smallIconProvider.smallIcon?.image
}
if let displayNameProvider = container as? DisplayNameProvider {
cell.label?.text = displayNameProvider.nameForDisplay
}
if let compContainer = initialContainer, container === compContainer {
cell.accessoryType = .checkmark
} else {
@@ -73,7 +73,7 @@ final class AddFeedFolderViewController: UITableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let container = containers[indexPath.row]
if let account = container as? Account, account.behaviors.contains(.disallowFeedInRootFolder) {
tableView.selectRow(at: nil, animated: false, scrollPosition: .none)
} else {
@@ -83,19 +83,19 @@ final class AddFeedFolderViewController: UITableViewController {
dismiss()
}
}
// MARK: Actions
@IBAction func cancel(_ sender: Any) {
dismiss()
}
}
private extension AddFeedFolderViewController {
func dismiss() {
dismiss(animated: true)
}
}
@@ -9,14 +9,14 @@
import UIKit
final class AddFeedSelectFolderTableViewCell: VibrantTableViewCell {
@IBOutlet weak var folderLabel: UILabel!
@IBOutlet weak var detailLabel: UILabel!
override func updateVibrancy(animated: Bool) {
super.updateVibrancy(animated: animated)
updateLabelVibrancy(folderLabel, color: labelColor, animated: animated)
updateLabelVibrancy(detailLabel, color: labelColor, animated: animated)
}
}
+31 -31
View File
@@ -13,24 +13,24 @@ import RSTree
import RSParser
final class AddFeedViewController: UITableViewController {
@IBOutlet weak var addButton: UIBarButtonItem!
@IBOutlet weak var urlTextField: UITextField!
@IBOutlet weak var urlTextFieldToSuperViewConstraint: NSLayoutConstraint!
@IBOutlet weak var nameTextField: UITextField!
static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 400.0)
private var folderLabel = ""
private var userCancelled = false
private let activityIndicator = UIActivityIndicatorView(style: .medium)
var initialFeed: String?
var initialFeedName: String?
var container: Container?
override func viewDidLoad() {
super.viewDidLoad()
@@ -39,77 +39,77 @@ final class AddFeedViewController: UITableViewController {
initialFeed = urlString.normalizedURL
}
}
urlTextField.autocorrectionType = .no
urlTextField.autocapitalizationType = .none
urlTextField.text = initialFeed
urlTextField.delegate = self
if initialFeed != nil {
addButton.isEnabled = true
}
nameTextField.text = initialFeedName
nameTextField.delegate = self
if let defaultContainer = AddFeedDefaultContainer.defaultContainer {
container = defaultContainer
} else {
addButton.isEnabled = false
}
updateFolderLabel()
tableView.register(UINib(nibName: "AddFeedSelectFolderTableViewCell", bundle: nil), forCellReuseIdentifier: "AddFeedSelectFolderTableViewCell")
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: urlTextField)
if initialFeed == nil {
urlTextField.becomeFirstResponder()
}
}
@IBAction func cancel(_ sender: Any) {
userCancelled = true
dismiss(animated: true)
}
@IBAction func add(_ sender: Any) {
let urlString = urlTextField.text ?? ""
let normalizedURLString = urlString.normalizedURL
guard !normalizedURLString.isEmpty, let url = URL(string: normalizedURLString) else {
return
}
guard let container = container else { return }
var account: Account?
if let containerAccount = container as? Account {
account = containerAccount
} else if let containerFolder = container as? Folder, let containerAccount = containerFolder.account {
account = containerAccount
}
if account!.hasFeed(withURL: url.absoluteString) {
presentError(AccountError.createErrorAlreadySubscribed)
return
}
addButton.isEnabled = false
addButton.customView = activityIndicator
addButton.customView?.isHidden = false
activityIndicator.startAnimating()
let feedName = (nameTextField.text?.isEmpty ?? true) ? nil : nameTextField.text
BatchUpdate.shared.start()
account!.createFeed(url: url.absoluteString, name: feedName, container: container, validateFeed: true) { result in
BatchUpdate.shared.end()
switch result {
case .success(let feed):
self.dismiss(animated: true)
@@ -124,11 +124,11 @@ final class AddFeedViewController: UITableViewController {
}
}
@objc func textDidChange(_ note: Notification) {
updateUI()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: "AddFeedSelectFolderTableViewCell", for: indexPath) as? AddFeedSelectFolderTableViewCell
@@ -138,7 +138,7 @@ final class AddFeedViewController: UITableViewController {
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 2 {
let navController = UIStoryboard.add.instantiateViewController(withIdentifier: "AddFeedFolderNavViewController") as! UINavigationController
@@ -149,7 +149,7 @@ final class AddFeedViewController: UITableViewController {
present(navController, animated: true)
}
}
}
// MARK: AddFeedFolderViewControllerDelegate
@@ -165,22 +165,22 @@ extension AddFeedViewController: AddFeedFolderViewControllerDelegate {
// MARK: UITextFieldDelegate
extension AddFeedViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
// MARK: Private
private extension AddFeedViewController {
func updateUI() {
addButton.isEnabled = (urlTextField.text?.mayBeURL ?? false)
}
func updateFolderLabel() {
if let containerName = (container as? DisplayNameProvider)?.nameForDisplay {
if container is Folder {
+22 -22
View File
@@ -16,13 +16,13 @@ final class AddFolderViewController: UITableViewController {
@IBOutlet private weak var nameTextField: UITextField!
@IBOutlet private weak var accountLabel: UILabel!
@IBOutlet private weak var accountPickerView: UIPickerView!
static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 400.0)
private var shouldDisplayPicker: Bool {
return accounts.count > 1
}
private var accounts: [Account]! {
didSet {
if let predefinedAccount = accounts.first(where: { $0.accountID == AppDefaults.shared.addFolderAccountID }) {
@@ -39,33 +39,33 @@ final class AddFolderViewController: UITableViewController {
accountLabel.text = selectedAccount.flatMap { ($0 as DisplayNameProvider).nameForDisplay }
}
}
override func viewDidLoad() {
super.viewDidLoad()
accounts = AccountManager.shared
.sortedActiveAccounts
.filter { !$0.behaviors.contains(.disallowFolderManagement) }
nameTextField.delegate = self
if shouldDisplayPicker {
accountPickerView.dataSource = self
accountPickerView.delegate = self
if let index = accounts.firstIndex(of: selectedAccount) {
accountPickerView.selectRow(index, inComponent: 0, animated: false)
}
} else {
accountPickerView.isHidden = true
}
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: nameTextField)
nameTextField.becomeFirstResponder()
}
private func didSelect(_ account: Account) {
AppDefaults.shared.addFolderAccountID = account.accountID
selectedAccount = account
@@ -74,7 +74,7 @@ final class AddFolderViewController: UITableViewController {
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true)
}
@IBAction func add(_ sender: Any) {
guard let folderName = nameTextField.text else {
return
@@ -93,42 +93,42 @@ final class AddFolderViewController: UITableViewController {
@objc func textDidChange(_ note: Notification) {
addButton.isEnabled = !(nameTextField.text?.isEmpty ?? false)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let defaultNumberOfRows = super.tableView(tableView, numberOfRowsInSection: section)
if section == 1 && !shouldDisplayPicker {
return defaultNumberOfRows - 1
}
return defaultNumberOfRows
}
}
extension AddFolderViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) ->Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return accounts.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return (accounts[row] as DisplayNameProvider).nameForDisplay
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
didSelect(accounts[row])
}
}
extension AddFolderViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
+4 -4
View File
@@ -12,10 +12,10 @@ final class SelectComboTableViewCell: VibrantTableViewCell {
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var label: UILabel!
override func updateVibrancy(animated: Bool) {
super.updateVibrancy(animated: animated)
let iconTintColor = isHighlighted || isSelected ? AppAssets.vibrantTextColor : UIColor.label
if animated {
UIView.animate(withDuration: Self.duration) {
@@ -24,8 +24,8 @@ final class SelectComboTableViewCell: VibrantTableViewCell {
} else {
self.icon.tintColor = iconTintColor
}
updateLabelVibrancy(label, color: labelColor, animated: animated)
}
}
+38 -38
View File
@@ -10,7 +10,7 @@ import RSCore
import Account
struct AppAssets {
static var accountBazQuxImage: UIImage = {
return UIImage(named: "accountBazQux")!
}()
@@ -90,39 +90,39 @@ struct AppAssets {
static var circleClosedImage: UIImage = {
return UIImage(systemName: "largecircle.fill.circle")!
}()
static var circleOpenImage: UIImage = {
return UIImage(systemName: "circle")!
}()
static var disclosureImage: UIImage = {
return UIImage(named: "disclosure")!
}()
static var copyImage: UIImage = {
return UIImage(systemName: "doc.on.doc")!
}()
static var deactivateImage: UIImage = {
UIImage(systemName: "minus.circle")!
}()
static var editImage: UIImage = {
UIImage(systemName: "square.and.pencil")!
}()
static var faviconTemplateImage: RSImage = {
return RSImage(named: "faviconTemplateImage")!
}()
static var filterImage: UIImage = {
UIImage(systemName: "line.3.horizontal.decrease")!
}()
static var folderOutlinePlus: UIImage = {
UIImage(systemName: "folder.badge.plus")!
}()
static var fullScreenBackgroundColor: UIColor = {
return UIColor(named: "fullScreenBackgroundColor")!
}()
@@ -130,91 +130,91 @@ struct AppAssets {
static var infoImage: UIImage = {
UIImage(systemName: "info.circle")!
}()
static var markAllAsReadImage: UIImage = {
return UIImage(named: "markAllAsRead")!
}()
static var markBelowAsReadImage: UIImage = {
return UIImage(systemName: "arrowtriangle.down.circle")!
}()
static var markAboveAsReadImage: UIImage = {
return UIImage(systemName: "arrowtriangle.up.circle")!
}()
static var mainFolderImage: IconImage = {
return IconImage(UIImage(systemName: "folder")!, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor)
}()
static var mainFolderImageNonIcon: UIImage = {
return UIImage(systemName: "folder")!.withRenderingMode(.alwaysOriginal).withTintColor(.secondaryLabel)
}()
static var moreImage: UIImage = {
return UIImage(systemName: "ellipsis.circle")!
}()
static var nextArticleImage: UIImage = {
return UIImage(systemName: "chevron.down")!
}()
static var nextUnreadArticleImage: UIImage = {
return UIImage(systemName: "chevron.down.circle")!
}()
static var plus: UIImage = {
UIImage(systemName: "plus")!
}()
static var prevArticleImage: UIImage = {
return UIImage(systemName: "chevron.up")!
}()
static var openInSidebarImage: UIImage = {
return UIImage(systemName: "arrow.turn.down.left")!
}()
static var primaryAccentColor: UIColor {
return UIColor(named: "primaryAccentColor")!
}
static var safariImage: UIImage = {
return UIImage(systemName: "safari")!
}()
static var searchFeedImage: IconImage = {
return IconImage(UIImage(systemName: "magnifyingglass")!, isSymbol: true)
}()
static var secondaryAccentColor: UIColor {
return UIColor(named: "secondaryAccentColor")!
}
static var sectionHeaderColor: UIColor = {
return UIColor(named: "sectionHeaderColor")!
}()
static var shareImage: UIImage = {
return UIImage(systemName: "square.and.arrow.up")!
}()
static var smartFeedImage: UIImage = {
return UIImage(systemName: "gear")!
}()
static var starColor: UIColor = {
return UIColor(named: "starColor")!
}()
static var starClosedImage: UIImage = {
return UIImage(systemName: "star.fill")!
}()
static var starOpenImage: UIImage = {
return UIImage(systemName: "star")!
}()
static var starredFeedImage: IconImage {
let image = UIImage(systemName: "star.fill")!
return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.starColor.cgColor)
@@ -223,12 +223,12 @@ struct AppAssets {
static var tickMarkColor: UIColor = {
return UIColor(named: "tickMarkColor")!
}()
static var timelineStarImage: UIImage = {
let image = UIImage(systemName: "star.fill")!
return image.withTintColor(AppAssets.starColor, renderingMode: .alwaysOriginal)
}()
static var todayFeedImage: IconImage {
let image = UIImage(systemName: "sun.max.fill")!
return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: UIColor.systemOrange.cgColor)
@@ -237,17 +237,17 @@ struct AppAssets {
static var trashImage: UIImage = {
return UIImage(systemName: "trash")!
}()
static var unreadCellIndicatorImage: IconImage {
let image = UIImage(systemName: "circle.fill")!
return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor)
}
static var unreadFeedImage: IconImage {
let image = UIImage(systemName: "largecircle.fill.circle")!
return IconImage(image, isSymbol: true, isBackgroundSuppressed: true, preferredColor: AppAssets.secondaryAccentColor.cgColor)
}
static var vibrantTextColor: UIColor = {
return UIColor(named: "vibrantTextColor")!
}()
@@ -283,5 +283,5 @@ struct AppAssets {
return AppAssets.accountTheOldReaderImage
}
}
}
+19 -19
View File
@@ -23,7 +23,7 @@ enum UserInterfaceColorPalette: Int, CustomStringConvertible, CaseIterable {
return NSLocalizedString("Dark", comment: "Dark")
}
}
}
extension Notification.Name {
@@ -33,16 +33,16 @@ extension Notification.Name {
final class AppDefaults {
static let defaultThemeName = "Default"
static let shared = AppDefaults()
private init() {}
static var store: UserDefaults = {
let appIdentifierPrefix = Bundle.main.object(forInfoDictionaryKey: "AppIdentifierPrefix") as! String
let suiteName = "\(appIdentifierPrefix)group.\(Bundle.main.bundleIdentifier!)"
return UserDefaults.init(suiteName: suiteName)!
}()
struct Key {
static let userInterfaceColorPalette = "userInterfaceColorPalette"
static let lastImageCacheFlushDate = "lastImageCacheFlushDate"
@@ -78,7 +78,7 @@ final class AppDefaults {
firstRunDate = Date()
return true
}()
static var userInterfaceColorPalette: UserInterfaceColorPalette {
get {
if let result = UserInterfaceColorPalette(rawValue: int(for: Key.userInterfaceColorPalette)) {
@@ -100,7 +100,7 @@ final class AppDefaults {
AppDefaults.setString(for: Key.addFeedAccountID, newValue)
}
}
var addFeedFolderName: String? {
get {
return AppDefaults.string(for: Key.addFeedFolderName)
@@ -109,7 +109,7 @@ final class AppDefaults {
AppDefaults.setString(for: Key.addFeedFolderName, newValue)
}
}
var addFolderAccountID: String? {
get {
return AppDefaults.string(for: Key.addFolderAccountID)
@@ -118,7 +118,7 @@ final class AppDefaults {
AppDefaults.setString(for: Key.addFolderAccountID, newValue)
}
}
var useSystemBrowser: Bool {
get {
return UserDefaults.standard.bool(forKey: Key.useSystemBrowser)
@@ -127,7 +127,7 @@ final class AppDefaults {
UserDefaults.standard.setValue(newValue, forKey: Key.useSystemBrowser)
}
}
var lastImageCacheFlushDate: Date? {
get {
return AppDefaults.date(for: Key.lastImageCacheFlushDate)
@@ -194,7 +194,7 @@ final class AppDefaults {
AppDefaults.setBool(for: Key.confirmMarkAllAsRead, newValue)
}
}
var isArticleContentJavascriptEnabled: Bool {
get {
return AppDefaults.bool(for: Key.articleContentJavascriptEnabled)
@@ -203,7 +203,7 @@ final class AppDefaults {
AppDefaults.setBool(for: Key.articleContentJavascriptEnabled, newValue)
}
}
var lastRefresh: Date? {
get {
return AppDefaults.date(for: Key.lastRefresh)
@@ -212,7 +212,7 @@ final class AppDefaults {
AppDefaults.setDate(for: Key.lastRefresh, newValue)
}
}
var timelineNumberOfLines: Int {
get {
return AppDefaults.int(for: Key.timelineNumberOfLines)
@@ -221,7 +221,7 @@ final class AppDefaults {
AppDefaults.setInt(for: Key.timelineNumberOfLines, newValue)
}
}
var timelineIconSize: IconSize {
get {
let rawValue = AppDefaults.store.integer(forKey: Key.timelineIconDimension)
@@ -231,7 +231,7 @@ final class AppDefaults {
AppDefaults.store.set(newValue.rawValue, forKey: Key.timelineIconDimension)
}
}
var currentThemeName: String? {
get {
return AppDefaults.string(for: Key.currentThemeName)
@@ -240,7 +240,7 @@ final class AppDefaults {
AppDefaults.setString(for: Key.currentThemeName, newValue)
}
}
static func registerDefaults() {
let defaults: [String : Any] = [Key.userInterfaceColorPalette: UserInterfaceColorPalette.automatic.rawValue,
Key.timelineGroupByFeed: false,
@@ -272,7 +272,7 @@ private extension AppDefaults {
static func string(for key: String) -> String? {
return UserDefaults.standard.string(forKey: key)
}
static func setString(for key: String, _ value: String?) {
UserDefaults.standard.set(value, forKey: key)
}
@@ -288,11 +288,11 @@ private extension AppDefaults {
static func int(for key: String) -> Int {
return AppDefaults.store.integer(forKey: key)
}
static func setInt(for key: String, _ x: Int) {
AppDefaults.store.set(x, forKey: key)
}
static func date(for key: String) -> Date? {
return AppDefaults.store.object(forKey: key) as? Date
}
@@ -317,5 +317,5 @@ private extension AppDefaults {
setInt(for: key, ComparisonResult.orderedDescending.rawValue)
}
}
}
+53 -53
View File
@@ -20,12 +20,12 @@ var appDelegate: AppDelegate!
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, UnreadCountProvider {
private let backgroundTaskDispatchQueue = DispatchQueue.init(label: "BGTaskScheduler")
private var waitBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
private var syncBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
var shuttingDown = false {
didSet {
if shuttingDown {
@@ -33,7 +33,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC
}
}
}
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "Application")
var widgetDataEncoder: WidgetDataEncoder!
@@ -46,10 +46,10 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC
}
}
}
var isSyncArticleStatusRunning = false
var isWaitingForSyncTasks = false
override init() {
super.init()
appDelegate = self
@@ -59,15 +59,15 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC
let documentAccountsFolder = documentFolder.appendingPathComponent("Accounts").absoluteString
let documentAccountsFolderPath = String(documentAccountsFolder.suffix(from: documentAccountsFolder.index(documentAccountsFolder.startIndex, offsetBy: 7)))
AccountManager.shared = AccountManager(accountsFolder: documentAccountsFolderPath)
let documentThemesFolder = documentFolder.appendingPathComponent("Themes").absoluteString
let documentThemesFolderPath = String(documentThemesFolder.suffix(from: documentAccountsFolder.index(documentThemesFolder.startIndex, offsetBy: 7)))
ArticleThemesManager.shared = ArticleThemesManager(folderPath: documentThemesFolderPath)
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountRefreshDidFinish(_:)), name: .AccountRefreshDidFinish, object: nil)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AppDefaults.registerDefaults()
@@ -75,23 +75,23 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC
if isFirstRun {
Self.logger.info("Is first run.")
}
if isFirstRun && !AccountManager.shared.anyAccountHasAtLeastOneFeed() {
let localAccount = AccountManager.shared.defaultAccount
DefaultFeedsImporter.importDefaultFeeds(account: localAccount)
}
registerBackgroundTasks()
CacheCleaner.purgeIfNecessary()
initializeDownloaders()
initializeHomeScreenQuickActions()
DispatchQueue.main.async {
self.unreadCount = AccountManager.shared.unreadCount
// Force the badge to update on launch.
self.updateBadge()
}
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .sound, .alert]) { (granted, error) in
if granted {
DispatchQueue.main.async {
@@ -102,21 +102,21 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC
UNUserNotificationCenter.current().delegate = self
UserNotificationManager.shared.start()
NetworkMonitor.shared.start()
ExtensionContainersFile.shared.start()
ExtensionFeedAddRequestFile.shared.start()
widgetDataEncoder = WidgetDataEncoder()
#if DEBUG
ArticleStatusSyncTimer.shared.update()
#endif
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
DispatchQueue.main.async {
self.resumeDatabaseProcessingIfNecessary()
@@ -126,7 +126,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC
}
}
}
func applicationWillTerminate(_ application: UIApplication) {
shuttingDown = true
}
@@ -142,33 +142,33 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC
}
// MARK: Notifications
@objc func unreadCountDidChange(_ note: Notification) {
if note.object is AccountManager {
unreadCount = AccountManager.shared.unreadCount
}
}
@objc func accountRefreshDidFinish(_ note: Notification) {
AppDefaults.shared.lastRefresh = Date()
}
// MARK: - API
func manualRefresh(errorHandler: @escaping (Error) -> ()) {
UIApplication.shared.connectedScenes.compactMap( { $0.delegate as? SceneDelegate } ).forEach {
$0.cleanUp(conditional: true)
}
AccountManager.shared.refreshAll(errorHandler: errorHandler)
}
func resumeDatabaseProcessingIfNecessary() {
if AccountManager.shared.isSuspended {
AccountManager.shared.resumeAll()
Self.logger.info("Application processing resumed.")
}
}
func prepareAccountsForBackground() {
updateBadge()
ExtensionFeedAddRequestFile.shared.suspend()
@@ -195,16 +195,16 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC
AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log)
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.list, .banner, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
defer { completionHandler() }
let userInfo = response.notification.request.content.userInfo
switch response.actionIdentifier {
case UserNotificationManager.ActionIdentifier.markAsRead:
handleMarkAsRead(userInfo: userInfo)
@@ -218,15 +218,15 @@ final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationC
})
}
}
}
}
// MARK: App Initialization
private extension AppDelegate {
private func initializeDownloaders() {
let tempDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
let imagesFolderURL = tempDir.appendingPathComponent("Images")
@@ -237,7 +237,7 @@ private extension AppDelegate {
let unreadTitle = NSLocalizedString("First Unread", comment: "First Unread")
let unreadIcon = UIApplicationShortcutIcon(systemImageName: "chevron.down.circle")
let unreadItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.FirstUnread", localizedTitle: unreadTitle, localizedSubtitle: nil, icon: unreadIcon, userInfo: nil)
let searchTitle = NSLocalizedString("Search", comment: "Search")
let searchIcon = UIApplicationShortcutIcon(systemImageName: "magnifyingglass")
let searchItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.ShowSearch", localizedTitle: searchTitle, localizedSubtitle: nil, icon: searchIcon, userInfo: nil)
@@ -248,38 +248,38 @@ private extension AppDelegate {
UIApplication.shared.shortcutItems = [addItem, searchItem, unreadItem]
}
}
// MARK: Go To Background
private extension AppDelegate {
func waitForSyncTasksToFinish() {
guard !isWaitingForSyncTasks && UIApplication.shared.applicationState == .background else { return }
isWaitingForSyncTasks = true
self.waitBackgroundUpdateTask = UIApplication.shared.beginBackgroundTask { [weak self] in
guard let self = self else { return }
self.completeProcessing(true)
Self.logger.info("Accounts wait for progress terminated for running too long.")
}
DispatchQueue.main.async { [weak self] in
self?.waitToComplete() { [weak self] suspend in
self?.completeProcessing(suspend)
}
}
}
func waitToComplete(completion: @escaping (Bool) -> Void) {
guard UIApplication.shared.applicationState == .background else {
Self.logger.info("App came back to foreground, no longer waiting.")
completion(false)
return
}
if AccountManager.shared.refreshInProgress || isSyncArticleStatusRunning || widgetDataEncoder.isRunning {
Self.logger.info("Waiting for sync to finish…")
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
@@ -290,7 +290,7 @@ private extension AppDelegate {
completion(true)
}
}
func completeProcessing(_ suspend: Bool) {
if suspend {
suspendApplication()
@@ -299,33 +299,33 @@ private extension AppDelegate {
self.waitBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
isWaitingForSyncTasks = false
}
func syncArticleStatus() {
guard !isSyncArticleStatusRunning else { return }
isSyncArticleStatusRunning = true
let completeProcessing = { [unowned self] in
self.isSyncArticleStatusRunning = false
UIApplication.shared.endBackgroundTask(self.syncBackgroundUpdateTask)
self.syncBackgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
}
self.syncBackgroundUpdateTask = UIApplication.shared.beginBackgroundTask {
completeProcessing()
Self.logger.info("Accounts sync processing terminated for running too long.")
}
DispatchQueue.main.async {
AccountManager.shared.syncArticleStatusAll() {
completeProcessing()
}
}
}
func suspendApplication() {
guard UIApplication.shared.applicationState == .background else { return }
AccountManager.shared.suspendNetworkAll()
AccountManager.shared.suspendDatabaseAll()
ArticleThemeDownloader.shared.cleanUp()
@@ -336,10 +336,10 @@ private extension AppDelegate {
sceneDelegate.suspend()
}
}
Self.logger.info("Application processing suspended.")
}
}
// MARK: Background Tasks
@@ -353,7 +353,7 @@ private extension AppDelegate {
self.performBackgroundFeedRefresh(with: task as! BGAppRefreshTask)
}
}
/// Schedules a background app refresh based on `AppDefaults.refreshInterval`.
func scheduleBackgroundFeedRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.ranchero.NetNewsWire.FeedRefresh")
@@ -369,7 +369,7 @@ private extension AppDelegate {
}
}
}
/// Performs background feed refresh.
/// - Parameter task: `BGAppRefreshTask`
/// - Warning: As of Xcode 11 beta 2, when triggered from the debugger this doesn't work.
@@ -406,11 +406,11 @@ private extension AppDelegate {
// Handle Notification Actions
private extension AppDelegate {
func handleMarkAsRead(userInfo: [AnyHashable: Any]) {
handleStatusNotification(userInfo: userInfo, statusKey: .read)
}
func handleMarkAsStarred(userInfo: [AnyHashable: Any]) {
handleStatusNotification(userInfo: userInfo, statusKey: .starred)
}
+11 -11
View File
@@ -16,9 +16,9 @@ enum ArticleExtractorButtonState {
}
final class ArticleExtractorButton: UIButton {
private var animatedLayer: CALayer?
var buttonState: ArticleExtractorButtonState = .off {
didSet {
if buttonState != oldValue {
@@ -39,7 +39,7 @@ final class ArticleExtractorButton: UIButton {
}
}
}
override var accessibilityLabel: String? {
get {
switch buttonState {
@@ -57,7 +57,7 @@ final class ArticleExtractorButton: UIButton {
super.accessibilityLabel = newValue
}
}
override func layoutSubviews() {
super.layoutSubviews()
guard case .animated = buttonState else {
@@ -66,31 +66,31 @@ final class ArticleExtractorButton: UIButton {
stripAnimatedSublayer()
addAnimatedSublayer(to: layer)
}
private func stripAnimatedSublayer() {
animatedLayer?.removeFromSuperlayer()
}
private func addAnimatedSublayer(to hostedLayer: CALayer) {
let image1 = AppAssets.articleExtractorOffTinted.cgImage!
let image2 = AppAssets.articleExtractorOnTinted.cgImage!
let images = [image1, image2, image1]
animatedLayer = CALayer()
let imageSize = AppAssets.articleExtractorOff.size
animatedLayer!.bounds = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
animatedLayer!.position = CGPoint(x: bounds.midX, y: bounds.midY)
hostedLayer.addSublayer(animatedLayer!)
let animation = CAKeyframeAnimation(keyPath: "contents")
animation.calculationMode = CAAnimationCalculationMode.linear
animation.keyTimes = [0, 0.5, 1]
animation.duration = 2
animation.values = images as [Any]
animation.repeatCount = HUGE
animatedLayer!.add(animation, forKey: "contents")
}
}
+7 -7
View File
@@ -11,13 +11,13 @@ import WebKit
import Articles
final class ArticleIconSchemeHandler: NSObject, WKURLSchemeHandler {
weak var coordinator: SceneCoordinator?
init(coordinator: SceneCoordinator) {
self.coordinator = coordinator
}
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
guard let url = urlSchemeTask.request.url, let coordinator = coordinator else {
@@ -37,12 +37,12 @@ final class ArticleIconSchemeHandler: NSObject, WKURLSchemeHandler {
let iconView = IconView(frame: CGRect(x: 0, y: 0, width: 48, height: 48))
iconView.iconImage = iconImage
let renderedImage = iconView.asImage()
guard let data = renderedImage.dataRepresentation() else {
urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist))
return
}
let headerFields = ["Cache-Control": "no-cache"]
if let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: headerFields) {
urlSchemeTask.didReceive(response)
@@ -51,10 +51,10 @@ final class ArticleIconSchemeHandler: NSObject, WKURLSchemeHandler {
}
}
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
urlSchemeTask.didFailWithError(URLError(.unknown))
}
}
+26 -26
View File
@@ -22,9 +22,9 @@ import UIKit
var prevButton: UIButton!
var background: UIView!
var shouldBeginEditing: Bool = true
weak private var resultsLabel: UILabel!
var resultsCount: UInt = 0 {
didSet {
updateUI()
@@ -35,30 +35,30 @@ import UIKit
updateUI()
}
}
weak var delegate: SearchBarDelegate?
override var keyCommands: [UIKeyCommand]? {
return [UIKeyCommand(title: "Exit Find", action: #selector(donePressed(_:)), input: UIKeyCommand.inputEscape)]
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
layer.backgroundColor = UIColor(named: "barBackgroundColor")?.cgColor ?? UIColor.white.cgColor
isOpaque = true
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: searchField)
}
private func updateUI() {
if resultsCount > 0 {
let format = NSLocalizedString("%d of %d", comment: "Results selection and count")
@@ -66,23 +66,23 @@ import UIKit
} else {
resultsLabel.text = NSLocalizedString("No results", comment: "No results")
}
nextButton.isEnabled = selectedResult < resultsCount
prevButton.isEnabled = resultsCount > 0 && selectedResult > 1
}
@discardableResult override func becomeFirstResponder() -> Bool {
searchField.becomeFirstResponder()
}
@discardableResult override func resignFirstResponder() -> Bool {
searchField.resignFirstResponder()
}
override var isFirstResponder: Bool {
searchField.isFirstResponder
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@@ -95,12 +95,12 @@ private extension ArticleSearchBar {
spacing = 8
layoutMargins.left = 8
layoutMargins.right = 8
background = UIView(frame: bounds)
background.backgroundColor = .systemGray5
background.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(background)
let doneButton = UIButton()
doneButton.setTitle(NSLocalizedString("Done", comment: "Done"), for: .normal)
doneButton.setTitleColor(UIColor.label, for: .normal)
@@ -109,14 +109,14 @@ private extension ArticleSearchBar {
doneButton.addTarget(self, action: #selector(donePressed), for: .touchUpInside)
doneButton.isEnabled = true
addArrangedSubview(doneButton)
let resultsLabel = UILabel()
searchField = UISearchTextField()
searchField.autocapitalizationType = .none
searchField.autocorrectionType = .no
searchField.returnKeyType = .search
searchField.delegate = self
resultsLabel.font = .systemFont(ofSize: UIFont.smallSystemFontSize)
resultsLabel.textColor = .secondaryLabel
resultsLabel.text = ""
@@ -124,17 +124,17 @@ private extension ArticleSearchBar {
resultsLabel.adjustsFontSizeToFitWidth = true
searchField.rightView = resultsLabel
searchField.rightViewMode = .always
self.resultsLabel = resultsLabel
addArrangedSubview(searchField)
prevButton = UIButton(type: .system)
prevButton.setImage(UIImage(systemName: "chevron.up"), for: .normal)
prevButton.accessibilityLabel = "Previous Result"
prevButton.isAccessibilityElement = true
prevButton.addTarget(self, action: #selector(previousPressed), for: .touchUpInside)
addArrangedSubview(prevButton)
nextButton = UIButton(type: .system)
nextButton.setImage(UIImage(systemName: "chevron.down"), for: .normal)
nextButton.accessibilityLabel = "Next Result"
@@ -145,25 +145,25 @@ private extension ArticleSearchBar {
}
private extension ArticleSearchBar {
@objc func textDidChange(_ notification: Notification) {
delegate?.searchBar?(self, textDidChange: searchField.text ?? "")
if searchField.text?.isEmpty ?? true {
searchField.rightViewMode = .never
} else {
searchField.rightViewMode = .always
}
}
@objc func nextPressed() {
delegate?.nextWasPressed?(self)
}
@objc func previousPressed() {
delegate?.previousWasPressed?(self)
}
@objc func donePressed(_ _: Any? = nil) {
delegate?.doneWasPressed?(self)
}
@@ -174,7 +174,7 @@ extension ArticleSearchBar: UITextFieldDelegate {
delegate?.nextWasPressed?(self)
return false
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return shouldBeginEditing
}
+66 -66
View File
@@ -13,7 +13,7 @@ import Articles
import SafariServices
final class ArticleViewController: UIViewController {
typealias State = (extractedArticle: ExtractedArticle?,
isShowingExtractedArticle: Bool,
articleExtractorButtonState: ArticleExtractorButtonState,
@@ -25,26 +25,26 @@ final class ArticleViewController: UIViewController {
@IBOutlet private weak var readBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var starBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var actionBarButtonItem: UIBarButtonItem!
@IBOutlet private var searchBar: ArticleSearchBar!
@IBOutlet private var searchBarBottomConstraint: NSLayoutConstraint!
private var defaultControls: [UIBarButtonItem]?
private var pageViewController: UIPageViewController!
private var currentWebViewController: WebViewController? {
return pageViewController?.viewControllers?.first as? WebViewController
}
private var articleExtractorButton: ArticleExtractorButton = {
let button = ArticleExtractorButton(type: .system)
button.frame = CGRect(x: 0, y: 0, width: 44.0, height: 44.0)
button.setImage(AppAssets.articleExtractorOff, for: .normal)
return button
}()
weak var coordinator: SceneCoordinator!
private let poppableDelegate = PoppableGestureRecognizerDelegate()
var article: Article? {
@@ -60,7 +60,7 @@ final class ArticleViewController: UIViewController {
updateUI()
}
}
var restoreScrollPosition: (isShowingExtractedArticle: Bool, articleWindowScrollY: Int)? {
didSet {
if let rsp = restoreScrollPosition {
@@ -68,7 +68,7 @@ final class ArticleViewController: UIViewController {
}
}
}
var currentState: State? {
guard let controller = currentWebViewController else { return nil}
return State(extractedArticle: controller.extractedArticle,
@@ -76,14 +76,14 @@ final class ArticleViewController: UIViewController {
articleExtractorButtonState: controller.articleExtractorButtonState,
windowScrollY: controller.windowScrollY)
}
var restoreState: State?
private let keyboardManager = KeyboardManager(type: .detail)
override var keyCommands: [UIKeyCommand]? {
return keyboardManager.keyCommands
}
override func viewDidLoad() {
super.viewDidLoad()
@@ -99,15 +99,15 @@ final class ArticleViewController: UIViewController {
])
fullScreenTapZone.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapNavigationBar)))
navigationItem.titleView = fullScreenTapZone
articleExtractorButton.addTarget(self, action: #selector(toggleArticleExtractor(_:)), for: .touchUpInside)
toolbarItems?.insert(UIBarButtonItem(customView: articleExtractorButton), at: 6)
if let parentNavController = navigationController?.parent as? UINavigationController {
poppableDelegate.navigationController = parentNavController
parentNavController.interactivePopGestureRecognizer?.delegate = poppableDelegate
}
pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [:])
pageViewController.delegate = self
pageViewController.dataSource = self
@@ -128,7 +128,7 @@ final class ArticleViewController: UIViewController {
view.topAnchor.constraint(equalTo: pageViewController.view.topAnchor),
view.bottomAnchor.constraint(equalTo: pageViewController.view.bottomAnchor)
])
let controller: WebViewController
if let state = restoreState {
controller = createWebViewController(article, updateView: false)
@@ -139,18 +139,18 @@ final class ArticleViewController: UIViewController {
} else {
controller = createWebViewController(article, updateView: true)
}
if let rsp = restoreScrollPosition {
controller.setScrollPosition(isShowingExtractedArticle: rsp.isShowingExtractedArticle, articleWindowScrollY: rsp.articleWindowScrollY)
}
articleExtractorButton.buttonState = controller.articleExtractorButtonState
self.pageViewController.setViewControllers([controller], direction: .forward, animated: false, completion: nil)
if AppDefaults.shared.logicalArticleFullscreenEnabled {
controller.hideBars()
}
// Search bar
searchBar.translatesAutoresizingMaskIntoConstraints = false
NotificationCenter.default.addObserver(self, selector: #selector(beginFind(_:)), name: .FindInArticle, object: nil)
@@ -158,10 +158,10 @@ final class ArticleViewController: UIViewController {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIWindow.keyboardWillChangeFrameNotification, object: nil)
searchBar.delegate = self
view.bringSubviewToFront(searchBar)
updateUI()
}
override func viewWillAppear(_ animated: Bool) {
let hideToolbars = AppDefaults.shared.logicalArticleFullscreenEnabled
if hideToolbars {
@@ -178,7 +178,7 @@ final class ArticleViewController: UIViewController {
coordinator.isArticleViewControllerPending = false
searchBar.shouldBeginEditing = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if searchBar != nil && !searchBar.isHidden {
@@ -186,12 +186,12 @@ final class ArticleViewController: UIViewController {
searchBar.shouldBeginEditing = false
}
}
override func viewSafeAreaInsetsDidChange() {
// This will animate if the show/hide bars animation is happening.
view.layoutIfNeeded()
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: any UIViewControllerTransitionCoordinator) {
// We only want to show bars when rotating to horizontalSizeClass == .regular
// (i.e., big) iPhones to resolve crash #4483.
@@ -199,9 +199,9 @@ final class ArticleViewController: UIViewController {
currentWebViewController?.showBars()
}
}
func updateUI() {
guard let article = article else {
articleExtractorButton.isEnabled = false
nextUnreadBarButtonItem.isEnabled = false
@@ -218,11 +218,11 @@ final class ArticleViewController: UIViewController {
nextArticleBarButtonItem.isEnabled = coordinator.isNextArticleAvailable
readBarButtonItem.isEnabled = true
starBarButtonItem.isEnabled = true
let permalinkPresent = article.preferredLink != nil
articleExtractorButton.isEnabled = permalinkPresent && !AppDefaults.shared.isDeveloperBuild
actionBarButtonItem.isEnabled = permalinkPresent
if article.status.read {
readBarButtonItem.image = AppAssets.circleOpenImage
readBarButtonItem.isEnabled = article.isAvailableToMarkUnread
@@ -232,7 +232,7 @@ final class ArticleViewController: UIViewController {
readBarButtonItem.isEnabled = true
readBarButtonItem.accLabelText = NSLocalizedString("Selected - Mark Article Unread", comment: "Selected - Mark Article Unread")
}
if article.status.starred {
starBarButtonItem.image = AppAssets.starClosedImage
starBarButtonItem.accLabelText = NSLocalizedString("Selected - Star Article", comment: "Selected - Star Article")
@@ -241,13 +241,13 @@ final class ArticleViewController: UIViewController {
starBarButtonItem.accLabelText = NSLocalizedString("Star Article", comment: "Star Article")
}
}
// MARK: Notifications
@objc dynamic func unreadCountDidChange(_ notification: Notification) {
updateUI()
}
@objc func statusesDidChange(_ note: Notification) {
guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set<String> else {
return
@@ -263,14 +263,14 @@ final class ArticleViewController: UIViewController {
@objc func contentSizeCategoryDidChange(_ note: Notification) {
currentWebViewController?.fullReload()
}
@objc func willEnterForeground(_ note: Notification) {
// The toolbar will come back on you if you don't hide it again
if AppDefaults.shared.logicalArticleFullscreenEnabled {
currentWebViewController?.hideBars()
}
}
// MARK: Actions
@objc func didTapNavigationBar() {
@@ -284,27 +284,27 @@ final class ArticleViewController: UIViewController {
@IBAction func toggleArticleExtractor(_ sender: Any) {
currentWebViewController?.toggleArticleExtractor()
}
@IBAction func nextUnread(_ sender: Any) {
coordinator.selectNextUnread()
}
@IBAction func prevArticle(_ sender: Any) {
coordinator.selectPrevArticle()
}
@IBAction func nextArticle(_ sender: Any) {
coordinator.selectNextArticle()
}
@IBAction func toggleRead(_ sender: Any) {
coordinator.toggleReadForCurrentArticle()
}
@IBAction func toggleStar(_ sender: Any) {
coordinator.toggleStarredForCurrentArticle()
}
@IBAction func showActivityDialog(_ sender: Any) {
currentWebViewController?.showActivityDialog(popOverBarButtonItem: actionBarButtonItem)
}
@@ -312,13 +312,13 @@ final class ArticleViewController: UIViewController {
@objc func toggleReaderView(_ sender: Any?) {
currentWebViewController?.toggleArticleExtractor()
}
// MARK: Keyboard Shortcuts
@objc func navigateToTimeline(_ sender: Any?) {
coordinator.navigateToTimeline()
}
// MARK: API
func focus() {
@@ -340,7 +340,7 @@ final class ArticleViewController: UIViewController {
func scrollPageUp() {
currentWebViewController?.scrollPageUp()
}
func stopArticleExtractorIfProcessing() {
currentWebViewController?.stopArticleExtractorIfProcessing()
}
@@ -348,7 +348,7 @@ final class ArticleViewController: UIViewController {
func openInAppBrowser() {
currentWebViewController?.openInAppBrowser()
}
func setScrollPosition(isShowingExtractedArticle: Bool, articleWindowScrollY: Int) {
currentWebViewController?.setScrollPosition(isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY)
}
@@ -361,29 +361,29 @@ public extension Notification.Name {
}
extension ArticleViewController: SearchBarDelegate {
func searchBar(_ searchBar: ArticleSearchBar, textDidChange searchText: String) {
currentWebViewController?.searchText(searchText) {
found in
searchBar.resultsCount = found.count
if let index = found.index {
searchBar.selectedResult = index + 1
}
}
}
func doneWasPressed(_ searchBar: ArticleSearchBar) {
NotificationCenter.default.post(name: .EndFindInArticle, object: nil)
}
func nextWasPressed(_ searchBar: ArticleSearchBar) {
if searchBar.selectedResult < searchBar.resultsCount {
currentWebViewController?.selectNextSearchResult()
searchBar.selectedResult += 1
}
}
func previousWasPressed(_ searchBar: ArticleSearchBar) {
if searchBar.selectedResult > 1 {
currentWebViewController?.selectPreviousSearchResult()
@@ -393,14 +393,14 @@ extension ArticleViewController: SearchBarDelegate {
}
extension ArticleViewController {
@objc func beginFind(_ _: Any? = nil) {
searchBar.isHidden = false
navigationController?.setToolbarHidden(true, animated: true)
currentWebViewController?.additionalSafeAreaInsets.bottom = searchBar.frame.height
searchBar.becomeFirstResponder()
}
@objc func endFind(_ _: Any? = nil) {
searchBar.resignFirstResponder()
searchBar.isHidden = true
@@ -408,13 +408,13 @@ extension ArticleViewController {
currentWebViewController?.additionalSafeAreaInsets.bottom = 0
currentWebViewController?.endSearch()
}
@objc func keyboardWillChangeFrame(_ notification: Notification) {
if !searchBar.isHidden,
let duration = notification.userInfo?[UIWindow.keyboardAnimationDurationUserInfoKey] as? Double,
let curveRaw = notification.userInfo?[UIWindow.keyboardAnimationCurveUserInfoKey] as? UInt,
let frame = notification.userInfo?[UIWindow.keyboardFrameEndUserInfoKey] as? CGRect {
let curve = UIView.AnimationOptions(rawValue: curveRaw)
let newHeight = view.safeAreaLayoutGuide.layoutFrame.maxY - frame.minY
currentWebViewController?.additionalSafeAreaInsets.bottom = newHeight + searchBar.frame.height + 10
@@ -424,26 +424,26 @@ extension ArticleViewController {
})
}
}
}
// MARK: WebViewControllerDelegate
extension ArticleViewController: WebViewControllerDelegate {
func webViewController(_ webViewController: WebViewController, articleExtractorButtonStateDidUpdate buttonState: ArticleExtractorButtonState) {
if webViewController === currentWebViewController {
articleExtractorButton.buttonState = buttonState
}
}
}
// MARK: UIPageViewControllerDataSource
extension ArticleViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let webViewController = viewController as? WebViewController,
let currentArticle = webViewController.article,
@@ -452,7 +452,7 @@ extension ArticleViewController: UIPageViewControllerDataSource {
}
return createWebViewController(article)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let webViewController = viewController as? WebViewController,
let currentArticle = webViewController.article,
@@ -461,7 +461,7 @@ extension ArticleViewController: UIPageViewControllerDataSource {
}
return createWebViewController(article)
}
}
// MARK: UIPageViewControllerDelegate
@@ -471,19 +471,19 @@ extension ArticleViewController: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
guard finished, completed else { return }
guard let article = currentWebViewController?.article else { return }
coordinator.selectArticle(article, animations: [.select, .scroll, .navigation])
articleExtractorButton.buttonState = currentWebViewController?.articleExtractorButtonState ?? .off
previousViewControllers.compactMap({ $0 as? WebViewController }).forEach({ $0.stopWebViewActivity() })
}
}
// MARK: UIGestureRecognizerDelegate
extension ArticleViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@@ -495,13 +495,13 @@ extension ArticleViewController: UIGestureRecognizerDelegate {
}
return false
}
}
// MARK: Private
private extension ArticleViewController {
func createWebViewController(_ article: Article?, updateView: Bool = true) -> WebViewController {
let controller = WebViewController()
controller.coordinator = coordinator
@@ -509,5 +509,5 @@ private extension ArticleViewController {
controller.setArticle(article, updateView: updateView)
return controller
}
}
@@ -15,37 +15,37 @@ final class ContextMenuPreviewViewController: UIViewController {
@IBOutlet weak var blogAuthorLabel: UILabel!
@IBOutlet weak var articleTitleLabel: UILabel!
@IBOutlet weak var dateTimeLabel: UILabel!
var article: Article!
override func viewDidLoad() {
super.viewDidLoad()
blogNameLabel.text = article.feed?.nameForDisplay ?? ""
blogAuthorLabel.text = article.byline()
articleTitleLabel.text = article.title ?? ""
let icon = IconView()
icon.iconImage = article.iconImage()
icon.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(icon)
NSLayoutConstraint.activate([
icon.widthAnchor.constraint(equalToConstant: 48),
icon.heightAnchor.constraint(equalToConstant: 48),
icon.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
icon.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20)
])
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .medium
dateTimeLabel.text = dateFormatter.string(from: article.logicalDatePublished)
// When in landscape the context menu preview will force this controller into a tiny
// view space. If it is documented anywhere what that is, I haven't found it. This
// set of magic numbers is what I worked out by testing a variety of phones.
let width: CGFloat
let heightPadding: CGFloat
if view.bounds.width > view.bounds.height {
@@ -56,7 +56,7 @@ final class ContextMenuPreviewViewController: UIViewController {
width = view.bounds.width
heightPadding = 8
}
view.setNeedsLayout()
view.layoutIfNeeded()
preferredContentSize = CGSize(width: width, height: dateTimeLabel.frame.maxY + heightPadding)
+7 -7
View File
@@ -12,27 +12,27 @@ final class FindInArticleActivity: UIActivity {
override var activityTitle: String? {
NSLocalizedString("Find in Article", comment: "Find in Article")
}
override var activityType: UIActivity.ActivityType? {
UIActivity.ActivityType(rawValue: "com.ranchero.NetNewsWire.find")
}
override var activityImage: UIImage? {
UIImage(systemName: "magnifyingglass", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular))
}
override class var activityCategory: UIActivity.Category {
.action
}
override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
true
}
override func prepare(withActivityItems activityItems: [Any]) {
}
override func perform() {
NotificationCenter.default.post(Notification(name: .FindInArticle))
activityDidFinish(true)
+81 -81
View File
@@ -14,63 +14,63 @@ import UIKit
}
open class ImageScrollView: UIScrollView {
@objc public enum ScaleMode: Int {
case aspectFill
case aspectFit
case widthFill
case heightFill
}
@objc public enum Offset: Int {
case beginning
case center
}
static let kZoomInFactorFromMinWhenDoubleTap: CGFloat = 2
@objc open var imageContentMode: ScaleMode = .widthFill
@objc open var initialOffset: Offset = .beginning
@objc public private(set) var zoomView: UIImageView? = nil
@objc open weak var imageScrollViewDelegate: ImageScrollViewDelegate?
var imageSize: CGSize = CGSize.zero
private var pointToCenterAfterResize: CGPoint = CGPoint.zero
private var scaleToRestoreAfterResize: CGFloat = 1.0
var maxScaleFromMinScale: CGFloat = 3.0
var zoomedFrame: CGRect {
return zoomView?.frame ?? CGRect.zero
}
override open var frame: CGRect {
willSet {
if frame.equalTo(newValue) == false && newValue.equalTo(CGRect.zero) == false && imageSize.equalTo(CGSize.zero) == false {
prepareToResize()
}
}
didSet {
if frame.equalTo(oldValue) == false && frame.equalTo(CGRect.zero) == false && imageSize.equalTo(CGSize.zero) == false {
recoverFromResizing()
}
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
@@ -78,135 +78,135 @@ open class ImageScrollView: UIScrollView {
decelerationRate = UIScrollView.DecelerationRate.fast
delegate = self
}
@objc public func adjustFrameToCenter() {
guard let unwrappedZoomView = zoomView else {
return
}
var frameToCenter = unwrappedZoomView.frame
// center horizontally
if frameToCenter.size.width < bounds.width {
frameToCenter.origin.x = (bounds.width - frameToCenter.size.width) / 2
} else {
frameToCenter.origin.x = 0
}
// center vertically
if frameToCenter.size.height < bounds.height {
frameToCenter.origin.y = (bounds.height - frameToCenter.size.height) / 2
} else {
frameToCenter.origin.y = 0
}
unwrappedZoomView.frame = frameToCenter
}
private func prepareToResize() {
let boundsCenter = CGPoint(x: bounds.midX, y: bounds.midY)
pointToCenterAfterResize = convert(boundsCenter, to: zoomView)
scaleToRestoreAfterResize = zoomScale
// If we're at the minimum zoom scale, preserve that by returning 0, which will be converted to the minimum
// allowable scale when the scale is restored.
if scaleToRestoreAfterResize <= minimumZoomScale + CGFloat(Float.ulpOfOne) {
scaleToRestoreAfterResize = 0
}
}
private func recoverFromResizing() {
setMaxMinZoomScalesForCurrentBounds()
// restore zoom scale, first making sure it is within the allowable range.
let maxZoomScale = max(minimumZoomScale, scaleToRestoreAfterResize)
zoomScale = min(maximumZoomScale, maxZoomScale)
// restore center point, first making sure it is within the allowable range.
// convert our desired center point back to our own coordinate space
let boundsCenter = convert(pointToCenterAfterResize, to: zoomView)
// calculate the content offset that would yield that center point
var offset = CGPoint(x: boundsCenter.x - bounds.size.width/2.0, y: boundsCenter.y - bounds.size.height/2.0)
// restore offset, adjusted to be within the allowable range
let maxOffset = maximumContentOffset()
let minOffset = minimumContentOffset()
var realMaxOffset = min(maxOffset.x, offset.x)
offset.x = max(minOffset.x, realMaxOffset)
realMaxOffset = min(maxOffset.y, offset.y)
offset.y = max(minOffset.y, realMaxOffset)
contentOffset = offset
}
private func maximumContentOffset() -> CGPoint {
return CGPoint(x: contentSize.width - bounds.width,y:contentSize.height - bounds.height)
}
private func minimumContentOffset() -> CGPoint {
return CGPoint.zero
}
// MARK: - Set up
open func setup() {
var topSupperView = superview
while topSupperView?.superview != nil {
topSupperView = topSupperView?.superview
}
// Make sure views have already layout with precise frame
topSupperView?.layoutIfNeeded()
}
// MARK: - Display image
@objc open func display(image: UIImage) {
if let zoomView = zoomView {
zoomView.removeFromSuperview()
}
zoomView = UIImageView(image: image)
zoomView!.isUserInteractionEnabled = true
addSubview(zoomView!)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTapGestureRecognizer(_:)))
tapGesture.numberOfTapsRequired = 2
zoomView!.addGestureRecognizer(tapGesture)
let downSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swipeUpGestureRecognizer(_:)))
downSwipeGesture.direction = .down
zoomView!.addGestureRecognizer(downSwipeGesture)
let upSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swipeDownGestureRecognizer(_:)))
upSwipeGesture.direction = .up
zoomView!.addGestureRecognizer(upSwipeGesture)
configureImageForSize(image.size)
adjustFrameToCenter()
}
private func configureImageForSize(_ size: CGSize) {
imageSize = size
contentSize = imageSize
setMaxMinZoomScalesForCurrentBounds()
zoomScale = minimumZoomScale
switch initialOffset {
case .beginning:
contentOffset = CGPoint.zero
case .center:
let xOffset = contentSize.width < bounds.width ? 0 : (contentSize.width - bounds.width)/2
let yOffset = contentSize.height < bounds.height ? 0 : (contentSize.height - bounds.height)/2
switch imageContentMode {
case .aspectFit:
contentOffset = CGPoint.zero
@@ -219,14 +219,14 @@ open class ImageScrollView: UIScrollView {
}
}
}
private func setMaxMinZoomScalesForCurrentBounds() {
// calculate min/max zoomscale
let xScale = bounds.width / imageSize.width // the scale needed to perfectly fit the image width-wise
let yScale = bounds.height / imageSize.height // the scale needed to perfectly fit the image height-wise
var minScale: CGFloat = 1
switch imageContentMode {
case .aspectFill:
minScale = max(xScale, yScale)
@@ -237,21 +237,21 @@ open class ImageScrollView: UIScrollView {
case .heightFill:
minScale = yScale
}
let maxScale = maxScaleFromMinScale*minScale
// don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.)
if minScale > maxScale {
minScale = maxScale
}
maximumZoomScale = maxScale
minimumZoomScale = minScale // * 0.999 // the multiply factor to prevent user cannot scroll page while they use this control in UIPageViewController
}
// MARK: - Gesture
@objc func doubleTapGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
// zoom out if it bigger than middle scale point. Else, zoom in
if zoomScale >= maximumZoomScale / 2.0 {
@@ -262,100 +262,100 @@ open class ImageScrollView: UIScrollView {
zoom(to: zoomRect, animated: true)
}
}
@objc func swipeUpGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == .ended {
imageScrollViewDelegate?.imageScrollViewDidGestureSwipeUp(imageScrollView: self)
}
}
@objc func swipeDownGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == .ended {
imageScrollViewDelegate?.imageScrollViewDidGestureSwipeDown(imageScrollView: self)
}
}
private func zoomRectForScale(_ scale: CGFloat, center: CGPoint) -> CGRect {
var zoomRect = CGRect.zero
// the zoom rect is in the content view's coordinates.
// at a zoom scale of 1.0, it would be the size of the imageScrollView's bounds.
// as the zoom scale decreases, so more content is visible, the size of the rect grows.
zoomRect.size.height = frame.size.height / scale
zoomRect.size.width = frame.size.width / scale
// choose an origin so as to get the right center.
zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0)
zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0)
return zoomRect
}
open func refresh() {
if let image = zoomView?.image {
display(image: image)
}
}
open func resize() {
self.configureImageForSize(self.imageSize)
}
}
extension ImageScrollView: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
imageScrollViewDelegate?.scrollViewDidScroll?(scrollView)
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
imageScrollViewDelegate?.scrollViewWillBeginDragging?(scrollView)
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
imageScrollViewDelegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
imageScrollViewDelegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
}
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
imageScrollViewDelegate?.scrollViewWillBeginDecelerating?(scrollView)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
imageScrollViewDelegate?.scrollViewDidEndDecelerating?(scrollView)
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
imageScrollViewDelegate?.scrollViewDidEndScrollingAnimation?(scrollView)
}
public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
imageScrollViewDelegate?.scrollViewWillBeginZooming?(scrollView, with: view)
}
public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
imageScrollViewDelegate?.scrollViewDidEndZooming?(scrollView, with: view, atScale: scale)
}
public func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
return false
}
@available(iOS 11.0, *)
public func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
imageScrollViewDelegate?.scrollViewDidChangeAdjustedContentInset?(scrollView)
}
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return zoomView
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
adjustFrameToCenter()
imageScrollViewDelegate?.scrollViewDidZoom?(scrollView)
}
}
+13 -13
View File
@@ -16,15 +16,15 @@ final class ImageTransition: NSObject, UIViewControllerAnimatedTransitioning {
var originFrame: CGRect!
var maskFrame: CGRect!
var originImage: UIImage!
init(controller: WebViewController) {
self.webViewController = controller
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if presenting {
animateTransitionPresenting(using: transitionContext)
@@ -32,18 +32,18 @@ final class ImageTransition: NSObject, UIViewControllerAnimatedTransitioning {
animateTransitionReturning(using: transitionContext)
}
}
private func animateTransitionPresenting(using transitionContext: UIViewControllerContextTransitioning) {
let imageView = UIImageView(image: originImage)
imageView.frame = originFrame
let fromView = transitionContext.view(forKey: .from)!
fromView.removeFromSuperview()
transitionContext.containerView.backgroundColor = AppAssets.fullScreenBackgroundColor
transitionContext.containerView.addSubview(imageView)
webViewController?.hideClickedImage()
UIView.animate(
@@ -61,27 +61,27 @@ final class ImageTransition: NSObject, UIViewControllerAnimatedTransitioning {
transitionContext.completeTransition(true)
})
}
private func animateTransitionReturning(using transitionContext: UIViewControllerContextTransitioning) {
let imageController = transitionContext.viewController(forKey: .from) as! ImageViewController
let imageView = UIImageView(image: originImage)
imageView.frame = imageController.zoomedFrame
let fromView = transitionContext.view(forKey: .from)!
let windowFrame = fromView.window!.frame
fromView.removeFromSuperview()
let toView = transitionContext.view(forKey: .to)!
transitionContext.containerView.addSubview(toView)
let maskingView = UIView()
let fullMaskFrame = CGRect(x: windowFrame.minX, y: maskFrame.minY, width: windowFrame.width, height: maskFrame.height)
let path = UIBezierPath(rect: fullMaskFrame)
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
maskingView.layer.mask = maskLayer
maskingView.addSubview(imageView)
transitionContext.containerView.addSubview(maskingView)
@@ -106,5 +106,5 @@ final class ImageTransition: NSObject, UIViewControllerAnimatedTransitioning {
}
})
}
}
+14 -14
View File
@@ -10,7 +10,7 @@ import UIKit
final class ImageViewController: UIViewController {
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var imageScrollView: ImageScrollView!
@@ -18,13 +18,13 @@ final class ImageViewController: UIViewController {
@IBOutlet weak var titleBackground: UIVisualEffectView!
@IBOutlet weak var titleLeading: NSLayoutConstraint!
@IBOutlet weak var titleTrailing: NSLayoutConstraint!
var image: UIImage!
var imageTitle: String?
var zoomedFrame: CGRect {
return imageScrollView.zoomedFrame
}
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(
@@ -34,23 +34,23 @@ final class ImageViewController: UIViewController {
)
]
}
override func viewDidLoad() {
super.viewDidLoad()
closeButton.imageView?.contentMode = .scaleAspectFit
closeButton.accessibilityLabel = NSLocalizedString("Close", comment: "Close")
shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Share")
imageScrollView.setup()
imageScrollView.imageScrollViewDelegate = self
imageScrollView.imageContentMode = .aspectFit
imageScrollView.initialOffset = .center
imageScrollView.display(image: image)
titleLabel.text = imageTitle ?? ""
layoutTitleLabel()
guard imageTitle != "" else {
titleBackground.removeFromSuperview()
return
@@ -64,7 +64,7 @@ final class ImageViewController: UIViewController {
self?.imageScrollView.resize()
})
}
@IBAction func share(_ sender: Any) {
guard let image = image else { return }
let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
@@ -72,11 +72,11 @@ final class ImageViewController: UIViewController {
activityViewController.popoverPresentationController?.sourceRect = shareButton.bounds
present(activityViewController, animated: true)
}
@IBAction func done(_ sender: Any) {
dismiss(animated: true)
}
private func layoutTitleLabel(){
let width = view.frame.width
let multiplier = traitCollection.userInterfaceIdiom == .pad ? CGFloat(0.1) : CGFloat(0.04)
@@ -93,10 +93,10 @@ extension ImageViewController: ImageScrollViewDelegate {
func imageScrollViewDidGestureSwipeUp(imageScrollView: ImageScrollView) {
dismiss(animated: true)
}
func imageScrollViewDidGestureSwipeDown(imageScrollView: ImageScrollView) {
dismiss(animated: true)
}
}
+8 -8
View File
@@ -9,17 +9,17 @@
import UIKit
final class OpenInBrowserActivity: UIActivity {
private var activityItems: [Any]?
override var activityTitle: String? {
return NSLocalizedString("Open in Browser", comment: "Open in Browser")
}
override var activityImage: UIImage? {
return UIImage(systemName: "globe", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .regular))
}
override var activityType: UIActivity.ActivityType? {
return UIActivity.ActivityType(rawValue: "com.rancharo.NetNewsWire-Evergreen.safari")
}
@@ -27,23 +27,23 @@ final class OpenInBrowserActivity: UIActivity {
override class var activityCategory: UIActivity.Category {
return .action
}
override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
return true
}
override func prepare(withActivityItems activityItems: [Any]) {
self.activityItems = activityItems
}
override func perform() {
guard let url = activityItems?.first(where: { $0 is URL }) as? URL else {
activityDidFinish(false)
return
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
activityDidFinish(true)
}
}
+7 -7
View File
@@ -10,7 +10,7 @@ import Foundation
import WebKit
final class PreloadedWebView: WKWebView {
private var isReady: Bool = false
private var readyCompletion: (() -> Void)?
@@ -19,17 +19,17 @@ final class PreloadedWebView: WKWebView {
super.init(frame: .zero, configuration: configuration)
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func preload() {
navigationDelegate = self
loadFileURL(ArticleRenderer.blank.url, allowingReadAccessTo: ArticleRenderer.blank.baseURL)
}
func ready(completion: @escaping () -> Void) {
if isReady {
completeRequest(completion: completion)
@@ -37,7 +37,7 @@ final class PreloadedWebView: WKWebView {
readyCompletion = completion
}
}
@objc func userDefaultsDidChange(_ sender: Any) {
Task { @MainActor in
if configuration.defaultWebpagePreferences.allowsContentJavaScript != AppDefaults.shared.isArticleContentJavascriptEnabled {
@@ -64,7 +64,7 @@ extension PreloadedWebView: WKNavigationDelegate {
// MARK: Private
private extension PreloadedWebView {
func completeRequest(completion: @escaping () -> Void) {
isReady = false
navigationDelegate = nil
+2 -2
View File
@@ -658,9 +658,9 @@ private extension WebViewController {
self.showFullScreenImage(image: image, clickMessage: clickMessage, webView: webView)
}
}
private func showFullScreenImage(image: UIImage, clickMessage: ImageClickMessage, webView: WKWebView) {
let y = CGFloat(clickMessage.y) + webView.safeAreaInsets.top
let rect = CGRect(x: CGFloat(clickMessage.x), y: y, width: CGFloat(clickMessage.width), height: CGFloat(clickMessage.height))
transition.originFrame = webView.convert(rect, to: nil)
+11 -11
View File
@@ -17,7 +17,7 @@ final class WebViewProvider: NSObject {
private let articleIconSchemeHandler: ArticleIconSchemeHandler
private let operationQueue = MainThreadOperationQueue()
private var queue = NSMutableArray()
init(coordinator: SceneCoordinator) {
articleIconSchemeHandler = ArticleIconSchemeHandler(coordinator: coordinator)
super.init()
@@ -27,12 +27,12 @@ final class WebViewProvider: NSObject {
func replenishQueueIfNeeded() {
operationQueue.add(WebViewProviderReplenishQueueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler))
}
func dequeueWebView(completion: @escaping (PreloadedWebView) -> ()) {
operationQueue.add(WebViewProviderDequeueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler, completion: completion))
operationQueue.add(WebViewProviderReplenishQueueOperation(queue: queue, articleIconSchemeHandler: articleIconSchemeHandler))
}
}
final class WebViewProviderReplenishQueueOperation: MainThreadOperation {
@@ -48,12 +48,12 @@ final class WebViewProviderReplenishQueueOperation: MainThreadOperation {
private var queue: NSMutableArray
private var articleIconSchemeHandler: ArticleIconSchemeHandler
init(queue: NSMutableArray, articleIconSchemeHandler: ArticleIconSchemeHandler) {
self.queue = queue
self.articleIconSchemeHandler = articleIconSchemeHandler
}
func run() {
while queue.count < minimumQueueDepth {
let webView = PreloadedWebView(articleIconSchemeHandler: articleIconSchemeHandler)
@@ -62,11 +62,11 @@ final class WebViewProviderReplenishQueueOperation: MainThreadOperation {
}
self.operationDelegate?.operationDidComplete(self)
}
}
final class WebViewProviderDequeueOperation: MainThreadOperation {
// MainThreadOperation
public var isCanceled = false
public var id: Int?
@@ -77,13 +77,13 @@ final class WebViewProviderDequeueOperation: MainThreadOperation {
private var queue: NSMutableArray
private var articleIconSchemeHandler: ArticleIconSchemeHandler
private var completion: (PreloadedWebView) -> ()
init(queue: NSMutableArray, articleIconSchemeHandler: ArticleIconSchemeHandler, completion: @escaping (PreloadedWebView) -> ()) {
self.queue = queue
self.articleIconSchemeHandler = articleIconSchemeHandler
self.completion = completion
}
func run() {
if let webView = queue.lastObject as? PreloadedWebView {
self.completion(webView)
@@ -93,11 +93,11 @@ final class WebViewProviderDequeueOperation: MainThreadOperation {
}
assertionFailure("Creating PreloadedWebView in \(#function); queue has run dry.")
let webView = PreloadedWebView(articleIconSchemeHandler: articleIconSchemeHandler)
webView.preload()
self.completion(webView)
self.operationDelegate?.operationDidComplete(self)
}
}
@@ -10,16 +10,16 @@ import Foundation
import WebKit
final class WrapperScriptMessageHandler: NSObject, WKScriptMessageHandler {
// We need to wrap a message handler to prevent a circlular reference
private weak var handler: WKScriptMessageHandler?
init(_ handler: WKScriptMessageHandler) {
self.handler = handler
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
handler?.userContentController(userContentController, didReceive: message)
}
}
+6 -6
View File
@@ -9,25 +9,25 @@
import UIKit
final class ArticleActivityItemSource: NSObject, UIActivityItemSource {
private let url: URL
private let subject: String?
init(url: URL, subject: String?) {
self.url = url
self.subject = subject
}
func activityViewControllerPlaceholderItem(_ : UIActivityViewController) -> Any {
return url
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return url
}
func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
return subject ?? ""
}
}
+3 -3
View File
@@ -47,11 +47,11 @@ final class IconView: UIView {
private var isSymbolImage: Bool {
return iconImage?.isSymbol ?? false
}
private var isBackgroundSuppressed: Bool {
return iconImage?.isBackgroundSuppressed ?? false
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
@@ -61,7 +61,7 @@ final class IconView: UIView {
super.init(coder: coder)
commonInit()
}
convenience init() {
self.init(frame: .zero)
}
@@ -21,23 +21,23 @@ final class AccountInspectorViewController: UITableViewController {
var isModal = false
weak var account: Account?
override func viewDidLoad() {
super.viewDidLoad()
guard let account = account else { return }
nameTextField.placeholder = account.defaultName
nameTextField.text = account.name
nameTextField.delegate = self
activeSwitch.isOn = account.isActive
navigationItem.title = account.nameForDisplay
if account.type != .onMyMac {
deleteAccountButton.setTitle(NSLocalizedString("Remove Account", comment: "Remove Account"), for: .normal)
}
if account.type != .cloudKit {
limitationsAndSolutionsButton.isHidden = true
}
@@ -46,11 +46,11 @@ final class AccountInspectorViewController: UITableViewController {
let doneBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done))
navigationItem.leftBarButtonItem = doneBarButtonItem
}
tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader")
}
override func viewWillDisappear(_ animated: Bool) {
account?.name = nameTextField.text
account?.isActive = activeSwitch.isOn
@@ -59,7 +59,7 @@ final class AccountInspectorViewController: UITableViewController {
@objc func done() {
dismiss(animated: true)
}
@IBAction func credentials(_ sender: Any) {
guard let account = account else { return }
switch account.type {
@@ -86,12 +86,12 @@ final class AccountInspectorViewController: UITableViewController {
break
}
}
@IBAction func deleteAccount(_ sender: Any) {
guard let account = account else {
return
}
let title = NSLocalizedString("Remove Account", comment: "Remove Account")
let message: String = {
switch account.type {
@@ -105,7 +105,7 @@ final class AccountInspectorViewController: UITableViewController {
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel)
alertController.addAction(cancelAction)
let markTitle = NSLocalizedString("Remove", comment: "Remove")
let markAction = UIAlertAction(title: markTitle, style: .destructive) { [weak self] (action) in
guard let self = self, let account = self.account else { return }
@@ -118,7 +118,7 @@ final class AccountInspectorViewController: UITableViewController {
}
alertController.addAction(markAction)
alertController.preferredAction = markAction
present(alertController, animated: true)
}
@@ -132,7 +132,7 @@ final class AccountInspectorViewController: UITableViewController {
// MARK: Table View
extension AccountInspectorViewController {
var hidesCredentialsSection: Bool {
guard let account = account else {
return true
@@ -147,7 +147,7 @@ extension AccountInspectorViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
guard let account = account else { return 0 }
if account == AccountManager.shared.defaultAccount {
return 1
} else if hidesCredentialsSection {
@@ -156,11 +156,11 @@ extension AccountInspectorViewController {
return super.numberOfSections(in: tableView)
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let account = account else { return nil }
@@ -172,16 +172,16 @@ extension AccountInspectorViewController {
return super.tableView(tableView, viewForHeaderInSection: section)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
if indexPath.section == 1, hidesCredentialsSection {
cell = super.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 2))
} else {
cell = super.tableView(tableView, cellForRowAt: indexPath)
}
return cell
}
@@ -191,17 +191,17 @@ extension AccountInspectorViewController {
}
return false
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
}
}
// MARK: UITextFieldDelegate
extension AccountInspectorViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
+35 -35
View File
@@ -12,52 +12,52 @@ import SafariServices
import UserNotifications
final class FeedInspectorViewController: UITableViewController {
static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 500.0)
var feed: Feed!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var notifyAboutNewArticlesSwitch: UISwitch!
@IBOutlet weak var alwaysShowReaderViewSwitch: UISwitch!
@IBOutlet weak var homePageLabel: InteractiveLabel!
@IBOutlet weak var feedURLLabel: InteractiveLabel!
private var headerView: InspectorIconHeaderView?
private var iconImage: IconImage? {
return IconImageCache.shared.imageForFeed(feed)
}
private let homePageIndexPath = IndexPath(row: 0, section: 1)
private var shouldHideHomePageSection: Bool {
return feed.homePageURL == nil
}
private var userNotificationSettings: UNNotificationSettings?
override func viewDidLoad() {
tableView.register(InspectorIconHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader")
navigationItem.title = feed.nameForDisplay
nameTextField.text = feed.nameForDisplay
notifyAboutNewArticlesSwitch.setOn(feed.isNotifyAboutNewArticles ?? false, animated: false)
alwaysShowReaderViewSwitch.setOn(feed.isArticleExtractorAlwaysOn ?? false, animated: false)
homePageLabel.text = feed.homePageURL
feedURLLabel.text = feed.url
NotificationCenter.default.addObserver(self, selector: #selector(feedIconDidBecomeAvailable(_:)), name: .feedIconDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updateNotificationSettings), name: UIApplication.willEnterForegroundNotification, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
updateNotificationSettings()
}
override func viewDidDisappear(_ animated: Bool) {
if nameTextField.text != feed.nameForDisplay {
let nameText = nameTextField.text ?? ""
@@ -65,12 +65,12 @@ final class FeedInspectorViewController: UITableViewController {
feed.rename(to: newName) { _ in }
}
}
// MARK: Notifications
@objc func feedIconDidBecomeAvailable(_ notification: Notification) {
headerView?.iconView.iconImage = iconImage
}
@IBAction func notifyAboutNewArticlesChanged(_ sender: Any) {
guard let settings = userNotificationSettings else {
notifyAboutNewArticlesSwitch.isOn = !notifyAboutNewArticlesSwitch.isOn
@@ -97,22 +97,22 @@ final class FeedInspectorViewController: UITableViewController {
}
}
}
@IBAction func alwaysShowReaderViewChanged(_ sender: Any) {
feed.isArticleExtractorAlwaysOn = alwaysShowReaderViewSwitch.isOn
}
@IBAction func done(_ sender: Any) {
dismiss(animated: true)
}
/// Returns a new indexPath, taking into consideration any
/// conditions that may require the tableView to be
/// displayed differently than what is setup in the storyboard.
private func shift(_ indexPath: IndexPath) -> IndexPath {
return IndexPath(row: indexPath.row, section: shift(indexPath.section))
}
/// Returns a new section, taking into consideration any
/// conditions that may require the tableView to be
/// displayed differently than what is setup in the storyboard.
@@ -123,7 +123,7 @@ final class FeedInspectorViewController: UITableViewController {
return section
}
}
// MARK: Table View
@@ -134,15 +134,15 @@ extension FeedInspectorViewController {
let numberOfSections = super.numberOfSections(in: tableView)
return shouldHideHomePageSection ? numberOfSections - 1 : numberOfSections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return super.tableView(tableView, numberOfRowsInSection: shift(section))
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: shift(section))
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: shift(indexPath))
if indexPath.section == 0 && indexPath.row == 1 {
@@ -154,11 +154,11 @@ extension FeedInspectorViewController {
}
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
super.tableView(tableView, titleForHeaderInSection: shift(section))
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if shift(section) == 0 {
headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as? InspectorIconHeaderView
@@ -168,12 +168,12 @@ extension FeedInspectorViewController {
return super.tableView(tableView, viewForHeaderInSection: shift(section))
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if shift(indexPath) == homePageIndexPath,
let homePageUrlString = feed.homePageURL,
let homePageUrl = URL(string: homePageUrlString) {
let safari = SFSafariViewController(url: homePageUrl)
safari.modalPresentationStyle = .pageSheet
present(safari, animated: true) {
@@ -181,24 +181,24 @@ extension FeedInspectorViewController {
}
}
}
}
// MARK: UITextFieldDelegate
extension FeedInspectorViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
// MARK: UNUserNotificationCenter
extension FeedInspectorViewController {
@objc
func updateNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
@@ -210,7 +210,7 @@ extension FeedInspectorViewController {
}
}
}
func notificationUpdateErrorAlert() -> UIAlertController {
let alert = UIAlertController(title: NSLocalizedString("Enable Notifications", comment: "Notifications"),
message: NSLocalizedString("Notifications need to be enabled in the Settings app.", comment: "Notifications need to be enabled in the Settings app."), preferredStyle: .alert)
@@ -223,5 +223,5 @@ extension FeedInspectorViewController {
alert.preferredAction = openSettings
return alert
}
}
+3 -3
View File
@@ -11,17 +11,17 @@ import UIKit
final class InspectorIconHeaderView: UITableViewHeaderFooterView {
var iconView = IconView()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
addSubview(iconView)
}
+2 -2
View File
@@ -9,7 +9,7 @@
import Intents
final class IntentHandler: INExtension {
override func handler(for intent: INIntent) -> Any {
switch intent {
case is AddWebFeedIntent:
@@ -18,5 +18,5 @@ final class IntentHandler: INExtension {
fatalError("Unhandled intent type: \(intent)")
}
}
}
+22 -22
View File
@@ -16,16 +16,16 @@ enum KeyboardType: String {
}
final class KeyboardManager {
private(set) var _keyCommands: [UIKeyCommand]
var keyCommands: [UIKeyCommand] {
guard !UIResponder.isFirstResponderTextField else { return [UIKeyCommand]() }
return _keyCommands
}
init(type: KeyboardType) {
_keyCommands = KeyboardManager.globalAuxilaryKeyCommands()
switch type {
case .sidebar:
_keyCommands.append(contentsOf: KeyboardManager.hardcodeFeedKeyCommands())
@@ -34,7 +34,7 @@ final class KeyboardManager {
default:
break
}
let globalFile = Bundle.main.path(forResource: KeyboardType.global.rawValue, ofType: "plist")!
let globalEntries = NSArray(contentsOfFile: globalFile)! as! [[String: Any]]
let globalCommands = globalEntries.compactMap { KeyboardManager.createKeyCommand(keyEntry: $0) }
@@ -44,7 +44,7 @@ final class KeyboardManager {
let specificEntries = NSArray(contentsOfFile: specificFile)! as! [[String: Any]]
_keyCommands.append(contentsOf: specificEntries.compactMap { KeyboardManager.createKeyCommand(keyEntry: $0) } )
}
static func createKeyCommand(title: String, action: String, input: String, modifiers: UIKeyModifierFlags) -> UIKeyCommand {
let selector = NSSelectorFromString(action)
let keyCommand = UIKeyCommand(title: title, image: nil, action: selector, input: input, modifierFlags: modifiers, propertyList: nil, alternates: [], discoverabilityTitle: nil, attributes: [], state: .on)
@@ -56,7 +56,7 @@ final class KeyboardManager {
}
private extension KeyboardManager {
static func createKeyCommand(keyEntry: [String: Any]) -> UIKeyCommand? {
guard let input = createKeyCommandInput(keyEntry: keyEntry) else { return nil }
let modifiers = createKeyModifierFlags(keyEntry: keyEntry)
@@ -75,7 +75,7 @@ private extension KeyboardManager {
static func createKeyCommandInput(keyEntry: [String: Any]) -> String? {
guard let key = keyEntry["key"] as? String else { return nil }
switch(key) {
case "[space]":
return "\u{0020}"
@@ -100,34 +100,34 @@ private extension KeyboardManager {
default:
return key
}
}
static func createKeyModifierFlags(keyEntry: [String: Any]) -> UIKeyModifierFlags {
var flags = UIKeyModifierFlags()
if keyEntry["shiftModifier"] as? Bool ?? false {
flags.insert(.shift)
}
if keyEntry["optionModifier"] as? Bool ?? false {
flags.insert(.alternate)
}
if keyEntry["commandModifier"] as? Bool ?? false {
flags.insert(.command)
}
if keyEntry["controlModifier"] as? Bool ?? false {
flags.insert(.control)
}
return flags
}
static func globalAuxilaryKeyCommands() -> [UIKeyCommand] {
var keys = [UIKeyCommand]()
let addNewFeedTitle = NSLocalizedString("New Feed", comment: "New Feed")
keys.append(KeyboardManager.createKeyCommand(title: addNewFeedTitle, action: "addNewFeed:", input: "n", modifiers: [.command]))
@@ -151,7 +151,7 @@ private extension KeyboardManager {
let gotoSettings = NSLocalizedString("Go To Settings", comment: "Go To Settings")
keys.append(KeyboardManager.createKeyCommand(title: gotoSettings, action: "goToSettings:", input: ",", modifiers: [.command]))
let articleSearchTitle = NSLocalizedString("Article Search", comment: "Article Search")
keys.append(KeyboardManager.createKeyCommand(title: articleSearchTitle, action: "articleSearch:", input: "f", modifiers: [.command, .alternate]))
@@ -169,7 +169,7 @@ private extension KeyboardManager {
return keys
}
static func hardcodeFeedKeyCommands() -> [UIKeyCommand] {
var keys = [UIKeyCommand]()
@@ -178,16 +178,16 @@ private extension KeyboardManager {
let nextDownTitle = NSLocalizedString("Select Next Down", comment: "Select Next Down")
keys.append(KeyboardManager.createKeyCommand(title: nextDownTitle, action: "selectNextDown:", input: UIKeyCommand.inputDownArrow, modifiers: []))
let getFeedInfo = NSLocalizedString("Get Feed Info", comment: "Get Feed Info")
keys.append(KeyboardManager.createKeyCommand(title: getFeedInfo, action: "showFeedInspector:", input: "i", modifiers: .command))
return keys
}
static func hardcodeArticleKeyCommands() -> [UIKeyCommand] {
var keys = [UIKeyCommand]()
let openInBrowserTitle = NSLocalizedString("Open In Browser", comment: "Open In Browser")
keys.append(KeyboardManager.createKeyCommand(title: openInBrowserTitle, action: "openInBrowser:", input: UIKeyCommand.inputRightArrow, modifiers: [.command]))
@@ -202,7 +202,7 @@ private extension KeyboardManager {
let toggleStarredTitle = NSLocalizedString("Toggle Starred Status", comment: "Toggle Starred Status")
keys.append(KeyboardManager.createKeyCommand(title: toggleStarredTitle, action: "toggleStarred:", input: "l", modifiers: [.command, .shift]))
let findInArticleTitle = NSLocalizedString("Find in Article", comment: "Find in Article")
keys.append(KeyboardManager.createKeyCommand(title: findInArticleTitle, action: "beginFind:", input: "f", modifiers: [.command]))
@@ -217,5 +217,5 @@ private extension KeyboardManager {
return keys
}
}
@@ -13,15 +13,15 @@ protocol MainFeedCollectionHeaderReusableViewDelegate: AnyObject {
}
class MainFeedCollectionHeaderReusableView: UICollectionReusableView {
var delegate: MainFeedCollectionHeaderReusableViewDelegate?
@IBOutlet weak var headerTitle: UILabel!
@IBOutlet weak var disclosureIndicator: UIImageView!
@IBOutlet weak var unreadCountLabel: UILabel!
private var unreadLabelWidthConstraint: NSLayoutConstraint?
override var accessibilityLabel: String? {
set {}
get {
@@ -43,10 +43,10 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView {
return NSLocalizedString("Collapsed", comment: "Disclosure button collapsed state for accessibility")
}
}
private var _unreadCount: Int = 0
var unreadCount: Int {
get {
return _unreadCount
@@ -57,14 +57,14 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView {
unreadCountLabel.text = newValue.formatted()
}
}
var disclosureExpanded = true {
didSet {
updateExpandedState(animate: true)
updateUnreadCount()
}
}
override func awakeFromNib() {
super.awakeFromNib()
unreadLabelWidthConstraint = unreadCountLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 80)
@@ -72,35 +72,35 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView {
configureUI()
addTapGesture()
}
func configureUI() {
headerTitle.textColor = traitCollection.userInterfaceIdiom == .pad ? .tertiaryLabel : .label
}
private func addTapGesture() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(containerHeaderTapped))
self.addGestureRecognizer(tapGesture)
self.isUserInteractionEnabled = true
}
@objc private func containerHeaderTapped() {
delegate?.mainFeedCollectionHeaderReusableViewDidTapDisclosureIndicator(self)
}
func configureContainer(withTitle title: String) {
headerTitle.text = title
disclosureIndicator.transform = .identity
}
func updateExpandedState(animate: Bool) {
if disclosureExpanded == false {
unreadLabelWidthConstraint = unreadCountLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 80)
} else {
unreadLabelWidthConstraint = unreadCountLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 0)
unreadLabelWidthConstraint?.isActive = false
}
let angle: CGFloat = disclosureExpanded ? 0 : -.pi / 2
let transform = CGAffineTransform(rotationAngle: angle)
let animations = {
@@ -112,7 +112,7 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView {
animations()
}
}
func updateUnreadCount() {
if !disclosureExpanded && unreadCount > 0 {
UIView.animate(withDuration: 0.3) {
@@ -124,5 +124,5 @@ class MainFeedCollectionHeaderReusableView: UICollectionReusableView {
}
}
}
}
@@ -13,12 +13,12 @@ import RSTree
class MainFeedCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var feedTitle: UILabel!
@IBOutlet weak var faviconView: IconView!
@IBOutlet weak var unreadCountLabel: UILabel!
private var faviconLeadingConstraint: NSLayoutConstraint?
var iconImage: IconImage? {
didSet {
faviconView.iconImage = iconImage
@@ -29,9 +29,9 @@ class MainFeedCollectionViewCell: UICollectionViewCell {
}
}
}
private var _unreadCount: Int = 0
var unreadCount: Int {
get {
return _unreadCount
@@ -46,7 +46,7 @@ class MainFeedCollectionViewCell: UICollectionViewCell {
unreadCountLabel.text = newValue.formatted()
}
}
/// If the feed is contained in a folder, the indentation level is 1
/// and the cell's favicon leading constrain is increased. Otherwise,
/// it has the standard leading constraint.
@@ -61,7 +61,7 @@ class MainFeedCollectionViewCell: UICollectionViewCell {
}
}
}
override var accessibilityLabel: String? {
set {}
get {
@@ -73,16 +73,16 @@ class MainFeedCollectionViewCell: UICollectionViewCell {
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
faviconLeadingConstraint = faviconView.leadingAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.leadingAnchor)
faviconLeadingConstraint?.isActive = true
}
override func updateConfiguration(using state: UICellConfigurationState) {
var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state)
switch (state.isHighlighted || state.isSelected || state.isFocused, traitCollection.userInterfaceIdiom) {
case (true, .pad):
backgroundConfig.backgroundColor = .tertiarySystemFill
@@ -114,6 +114,6 @@ class MainFeedCollectionViewCell: UICollectionViewCell {
}
self.backgroundConfiguration = backgroundConfig
}
}
@@ -13,14 +13,14 @@ protocol MainFeedCollectionViewFolderCellDelegate: AnyObject {
}
class MainFeedCollectionViewFolderCell: UICollectionViewCell {
@IBOutlet weak var folderTitle: UILabel!
@IBOutlet weak var faviconView: IconView!
@IBOutlet weak var unreadCountLabel: UILabel!
@IBOutlet weak var disclosureButton: UIButton!
var delegate: MainFeedCollectionViewFolderCellDelegate?
private var _unreadCount: Int = 0
var unreadCount: Int {
get {
@@ -37,7 +37,7 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell {
unreadCountLabel.text = newValue.formatted()
}
}
var iconImage: IconImage? {
didSet {
faviconView.iconImage = iconImage
@@ -48,19 +48,19 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell {
}
}
}
var disclosureExpanded = true {
didSet {
updateExpandedState(animate: true)
updateUnreadCount()
}
}
override func awakeFromNib() {
super.awakeFromNib()
disclosureButton.addInteraction(UIPointerInteraction())
}
func updateExpandedState(animate: Bool) {
let angle: CGFloat = disclosureExpanded ? 0 : -.pi / 2
let transform = CGAffineTransform(rotationAngle: angle)
@@ -73,7 +73,7 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell {
animations()
}
}
func updateUnreadCount() {
if !disclosureExpanded && unreadCount > 0 && unreadCountLabel.alpha != 1 {
UIView.animate(withDuration: 0.3) {
@@ -85,18 +85,18 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell {
}
}
}
@IBAction
func toggleDisclosure() {
setDisclosure(isExpanded: !disclosureExpanded, animated: true)
delegate?.mainFeedCollectionFolderViewCellDisclosureDidToggle(self, expanding: disclosureExpanded)
}
func setDisclosure(isExpanded: Bool, animated: Bool) {
disclosureExpanded = isExpanded
}
override var accessibilityLabel: String? {
set {}
get {
@@ -108,10 +108,10 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell {
}
}
}
override func updateConfiguration(using state: UICellConfigurationState) {
var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state)
switch (state.isHighlighted || state.isSelected || state.isFocused, traitCollection.userInterfaceIdiom) {
case (true, .pad):
backgroundConfig.backgroundColor = .tertiarySystemFill
@@ -129,12 +129,12 @@ class MainFeedCollectionViewFolderCell: UICollectionViewCell {
folderTitle.font = UIFont.preferredFont(forTextStyle: .body)
unreadCountLabel.font = UIFont.preferredFont(forTextStyle: .body)
}
if state.cellDropState == .targeted {
backgroundConfig.backgroundColor = .tertiarySystemFill
}
self.backgroundConfiguration = backgroundConfig
}
}
@@ -11,13 +11,13 @@ import Foundation
final class MainFeedRowIdentifier: NSObject, NSCopying {
var indexPath: IndexPath
init(indexPath: IndexPath) {
self.indexPath = indexPath
}
func copy(with zone: NSZone? = nil) -> Any {
return self
}
}
@@ -21,20 +21,20 @@ extension MainFeedCollectionViewController: UICollectionViewDragDelegate {
guard let node = coordinator.nodeFor(indexPath), let feed = node.representedObject as? Feed else {
return [UIDragItem]()
}
let data = feed.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]
}
}
@@ -18,7 +18,7 @@ import UniformTypeIdentifiers
extension MainFeedCollectionViewController: UICollectionViewDropDelegate {
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: any UICollectionViewDropCoordinator) {
guard let dragItem = coordinator.items.first?.dragItem,
let dragNode = dragItem.localObject as? Node,
@@ -26,17 +26,17 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate {
let destIndexPath = coordinator.destinationIndexPath else {
return
}
let isFolderDrop: Bool = {
if self.coordinator.nodeFor(destIndexPath)?.representedObject is Folder, let propCell = collectionView.cellForItem(at: destIndexPath) {
return coordinator.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 self.coordinator.nodeFor(destIndexPath)
} else {
@@ -48,7 +48,7 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate {
return nil
}
}
}()
// Now we start looking for the parent container
@@ -60,22 +60,22 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate {
return self.coordinator.rootNode.childAtIndex(destIndexPath.section)?.representedObject as? Account
}
}()
guard let destination = destinationContainer, let feed = dragNode.representedObject as? Feed else { return }
if source.account == destination.account {
moveFeedInAccount(feed: feed, sourceContainer: source, destinationContainer: destination)
} else {
moveFeedBetweenAccounts(feed: feed, sourceContainer: source, destinationContainer: destination)
}
}
func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: any UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
guard let destIndexPath = destinationIndexPath, destIndexPath.section > 0, collectionView.hasActiveDrag else {
return UICollectionViewDropProposal(operation: .forbidden)
}
guard let destFeed = coordinator.nodeFor(destIndexPath)?.representedObject as? SidebarItem,
let destAccount = destFeed.account,
let destCell = collectionView.cellForItem(at: destIndexPath) else {
@@ -101,17 +101,17 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate {
return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
}
func collectionView(_ collectionView: UICollectionView, canHandle session: any UIDropSession) -> Bool {
return session.localDragSession != nil
}
func collectionView(_ collectionView: UICollectionView, dropSessionDidEnd session: UIDropSession) {
}
func moveFeedInAccount(feed: Feed, sourceContainer: Container, destinationContainer: Container) {
guard sourceContainer !== destinationContainer else { return }
BatchUpdate.shared.start()
sourceContainer.account?.moveFeed(feed, from: sourceContainer, to: destinationContainer) { result in
BatchUpdate.shared.end()
@@ -123,11 +123,11 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate {
}
}
}
func moveFeedBetweenAccounts(feed: Feed, sourceContainer: Container, destinationContainer: Container) {
if let existingFeed = destinationContainer.account?.existingFeed(withURL: feed.url) {
BatchUpdate.shared.start()
destinationContainer.account?.addFeed(existingFeed, to: destinationContainer) { result in
switch result {
@@ -146,9 +146,9 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate {
self.presentError(error)
}
}
} else {
BatchUpdate.shared.start()
destinationContainer.account?.createFeed(url: feed.url, name: feed.editedName, container: destinationContainer, validateFeed: false) { result in
switch result {
@@ -167,8 +167,8 @@ extension MainFeedCollectionViewController: UICollectionViewDropDelegate {
self.presentError(error)
}
}
}
}
}
File diff suppressed because it is too large. Load diff
+7 -7
View File
@@ -10,10 +10,10 @@ import UIKit
import Account
final class RefreshProgressView: UIView {
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var label: UILabel!
override func awakeFromNib() {
NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .combinedRefreshProgressDidChange, object: nil)
@@ -24,7 +24,7 @@ final class RefreshProgressView: UIView {
isAccessibilityElement = true
accessibilityTraits = [.updatesFrequently, .notEnabled]
}
func update() {
if !AccountManager.shared.combinedRefreshProgress.isComplete {
progressChanged(animated: false)
@@ -50,7 +50,7 @@ final class RefreshProgressView: UIView {
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: Private
@@ -68,7 +68,7 @@ private extension RefreshProgressView {
if isInViewHierarchy {
progressView.setProgress(1, animated: animated)
}
func completeLabel() {
// Check that there are no pending downloads.
if AccountManager.shared.combinedRefreshProgress.isComplete {
@@ -101,7 +101,7 @@ private extension RefreshProgressView {
}
}
}
func updateRefreshLabel() {
if let accountLastArticleFetchEndTime = AccountManager.shared.lastArticleFetchEndTime {
@@ -131,5 +131,5 @@ private extension RefreshProgressView {
self?.scheduleUpdateRefreshLabel()
}
}
}
@@ -12,7 +12,7 @@ import Articles
struct MainTimelineCellData {
private static let noText = NSLocalizedString("(No Text)", comment: "No Text")
let title: String
let attributedTitle: NSAttributedString
let summary: String
@@ -38,7 +38,7 @@ struct MainTimelineCellData {
} else {
self.summary = truncatedSummary
}
self.dateString = ArticleStringFormatter.dateString(article.logicalDatePublished)
if let feedName = feedName {
@@ -47,7 +47,7 @@ struct MainTimelineCellData {
else {
self.feedName = ""
}
if let byline = byline {
self.byline = byline
} else {
@@ -63,7 +63,7 @@ struct MainTimelineCellData {
self.starred = article.status.starred
self.numberOfLines = numberOfLines
self.iconSize = iconSize
}
init() { //Empty
@@ -81,5 +81,5 @@ struct MainTimelineCellData {
self.numberOfLines = 0
self.iconSize = .medium
}
}
@@ -21,15 +21,15 @@ class MainTimelineFeedCell: UITableViewCell {
configure(cellData)
}
}
var isPreview: Bool = false
override func awakeFromNib() {
super.awakeFromNib()
indicatorView.alpha = 0.0
configureStackView()
}
private func configureStackView() {
switch traitCollection.preferredContentSizeCategory {
case .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge:
@@ -42,11 +42,11 @@ class MainTimelineFeedCell: UITableViewCell {
metaDataStackView.distribution = .fill
}
}
private func configure(_ cellData: MainTimelineCellData) {
updateIndicatorView(cellData)
articleTitle.numberOfLines = cellData.numberOfLines
applyTitleTextWithAttributes(configurationState)
if cellData.showFeedName == .feed {
@@ -56,10 +56,10 @@ class MainTimelineFeedCell: UITableViewCell {
} else if cellData.showFeedName == .none {
authorByLine.text = ""
}
articleDate.text = cellData.dateString
}
private func updateIndicatorView(_ cellData: MainTimelineCellData) {
if cellData.read == false {
if indicatorView.alpha == 0.0 {
@@ -86,7 +86,7 @@ class MainTimelineFeedCell: UITableViewCell {
}
}
}
private func applyTitleTextWithAttributes(_ state: UICellConfigurationState) {
let attributedCellText = NSMutableAttributedString()
let isSelected = state.isSelected || state.isHighlighted || state.isFocused || state.isSwiped
@@ -119,17 +119,17 @@ class MainTimelineFeedCell: UITableViewCell {
}
articleTitle.attributedText = attributedCellText
}
override func updateConfiguration(using state: UICellConfigurationState) {
super.updateConfiguration(using: state)
var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state)
backgroundConfig.cornerRadius = 20
if traitCollection.userInterfaceIdiom == .pad {
backgroundConfig.edgesAddingLayoutMarginsToBackgroundInsets = [.leading, .trailing]
backgroundConfig.backgroundInsets = NSDirectionalEdgeInsets(top: 0, leading: !isPreview ? -4 : -12, bottom: 0, trailing: !isPreview ? -4 : -12)
}
if state.isSelected || state.isHighlighted || state.isFocused || state.isSwiped {
backgroundConfig.backgroundColor = AppAssets.primaryAccentColor
applyTitleTextWithAttributes(state)
@@ -140,9 +140,9 @@ class MainTimelineFeedCell: UITableViewCell {
articleDate.textColor = .secondaryLabel
authorByLine.textColor = .secondaryLabel
}
self.backgroundConfiguration = backgroundConfig
}
}
@@ -9,29 +9,29 @@
import UIKit
class MainTimelineIconFeedCell: UITableViewCell {
@IBOutlet weak var articleTitle: UILabel!
@IBOutlet weak var authorByLine: UILabel!
@IBOutlet weak var iconView: IconView!
@IBOutlet weak var indicatorView: IconView!
@IBOutlet weak var articleDate: UILabel!
@IBOutlet weak var metaDataStackView: UIStackView!
var cellData: MainTimelineCellData! {
didSet {
configure(cellData)
}
}
var isPreview: Bool = false
override func awakeFromNib() {
super.awakeFromNib()
indicatorView.alpha = 0.0
iconView.translatesAutoresizingMaskIntoConstraints = false
configureStackView()
}
private func configureStackView() {
switch traitCollection.preferredContentSizeCategory {
case .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge:
@@ -44,13 +44,13 @@ class MainTimelineIconFeedCell: UITableViewCell {
metaDataStackView.distribution = .fill
}
}
private func configure(_ cellData: MainTimelineCellData) {
updateIndicatorView(cellData)
articleTitle.numberOfLines = cellData.numberOfLines
applyTitleTextWithAttributes(configurationState)
if cellData.showFeedName == .feed {
authorByLine.text = cellData.feedName
} else if cellData.showFeedName == .byline {
@@ -58,34 +58,34 @@ class MainTimelineIconFeedCell: UITableViewCell {
} else if cellData.showFeedName == .none {
authorByLine.text = ""
}
setIconImage(cellData.iconImage, with: cellData.iconSize)
articleDate.text = cellData.dateString
}
private func setIconImage(_ iconImage: IconImage?, with size: IconSize) {
iconView.iconImage = iconImage
updateIconViewSizeConstraints(to: size.size)
}
func setIconImage(_ iconImage: IconImage?) {
iconView.iconImage = iconImage
}
private func updateIconViewSizeConstraints(to size: CGSize) {
for constraint in iconView.constraints {
constraint.isActive = false
}
NSLayoutConstraint.activate([
iconView.widthAnchor.constraint(equalToConstant: size.width),
iconView.heightAnchor.constraint(equalToConstant: size.height)
])
setNeedsLayout()
}
private func updateIndicatorView(_ cellData: MainTimelineCellData) {
if cellData.read == false {
if indicatorView.alpha == 0.0 {
@@ -112,12 +112,12 @@ class MainTimelineIconFeedCell: UITableViewCell {
}
}
}
private func applyTitleTextWithAttributes(_ state: UICellConfigurationState) {
let attributedCellText = NSMutableAttributedString()
let isSelected = state.isSelected || state.isHighlighted || state.isFocused || state.isSwiped
if cellData.title != "" {
let paragraphStyle = NSMutableParagraphStyle()
@@ -148,17 +148,17 @@ class MainTimelineIconFeedCell: UITableViewCell {
}
articleTitle.attributedText = attributedCellText
}
override func updateConfiguration(using state: UICellConfigurationState) {
super.updateConfiguration(using: state)
var backgroundConfig = UIBackgroundConfiguration.listCell().updated(for: state)
backgroundConfig.cornerRadius = 20
if traitCollection.userInterfaceIdiom == .pad {
backgroundConfig.edgesAddingLayoutMarginsToBackgroundInsets = [.leading, .trailing]
backgroundConfig.backgroundInsets = NSDirectionalEdgeInsets(top: 0, leading: !isPreview ? -4 : -12, bottom: 0, trailing: !isPreview ? -4 : -12)
}
if state.isSelected || state.isHighlighted || state.isFocused || state.isSwiped {
backgroundConfig.backgroundColor = AppAssets.primaryAccentColor
applyTitleTextWithAttributes(state)
@@ -169,9 +169,9 @@ class MainTimelineIconFeedCell: UITableViewCell {
articleDate.textColor = .secondaryLabel
authorByLine.textColor = .secondaryLabel
}
self.backgroundConfiguration = backgroundConfig
}
}
@@ -13,6 +13,6 @@ final class MainTimelineDataSource<SectionIdentifierType, ItemIdentifierType>: U
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
}
+106 -106
View File
@@ -18,7 +18,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
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?
@@ -28,7 +28,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
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)
@@ -97,7 +97,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
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.
@@ -105,7 +105,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
return keyboardManager.keyCommands
}
private var navigationBarTitleLabel: UILabel {
let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: .subheadline).bold()
@@ -118,7 +118,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
label.addInteraction(pointerInteraction)
return label
}
private var navigationBarSubtitleTitleLabel: UILabel {
let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: .footnote)
@@ -129,7 +129,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
label.addGestureRecognizer(tap)
return label
}
override var canBecomeFirstResponder: Bool {
return true
}
@@ -137,7 +137,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
override func viewDidLoad() {
assert(coordinator != nil)
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
@@ -156,7 +156,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
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
@@ -168,43 +168,43 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
NSLocalizedString("All Articles", comment: "All Articles")
]
navigationItem.searchController = searchController
if traitCollection.userInterfaceIdiom == .pad {
searchController.searchBar.selectedScopeButtonIndex = 1
navigationItem.searchBarPlacementAllowsExternalIntegration = true
}
definesPresentationContext = true
// Configure the table
tableView.dataSource = dataSource
tableView.isPrefetchingEnabled = false
numberOfTextLines = AppDefaults.shared.timelineNumberOfLines
iconSize = AppDefaults.shared.timelineIconSize
refreshControl = UIRefreshControl()
refreshControl!.addTarget(self, action: #selector(refreshAccounts(_:)), for: .valueChanged)
configureToolbar()
resetUI(resetScroll: true)
// Load the table and then scroll to the saved position if available
applyChanges(animated: false) {
if let restoreIndexPath = self.timelineMiddleIndexPath {
self.tableView.scrollToRow(at: restoreIndexPath, at: .middle, animated: false)
}
}
// Disable swipe back on iPad Mice
guard let gesture = self.navigationController?.interactivePopGestureRecognizer as? UIPanGestureRecognizer else {
return
}
gesture.allowedScrollTypesMask = []
navigationItem.titleView = navigationBarTitleLabel
navigationItem.subtitleView = navigationBarSubtitleTitleLabel
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.isToolbarHidden = false
@@ -217,7 +217,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
updateNavigationBarTitle(coordinator?.timelineFeed?.nameForDisplay ?? "")
updateNavigationBarSubtitle("")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
isTimelineViewControllerPending = false
@@ -235,9 +235,9 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
}
}
}
// MARK: Actions
@objc func openInBrowser(_ sender: Any?) {
assert(coordinator != nil)
coordinator?.showBrowserForCurrentArticle()
@@ -247,7 +247,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
assert(coordinator != nil)
coordinator?.showInAppBrowser()
}
@IBAction func toggleFilter(_ sender: Any) {
assert(coordinator != nil)
coordinator?.toggleReadArticlesFilter()
@@ -260,29 +260,29 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
@IBAction func markAllAsRead(_ sender: Any) {
let title = NSLocalizedString("Mark All as Read", comment: "Mark All as Read")
if let source = sender as? UIBarButtonItem {
MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: source) { [weak self] in
self?.markAllAsReadInTimeline()
}
}
if let _ = sender as? UIKeyCommand {
guard let indexPath = tableView.indexPathForSelectedRow, let contentView = tableView.cellForRow(at: indexPath)?.contentView else {
return
}
MarkAsReadAlertController.confirm(self, coordinator: coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in
self?.markAllAsReadInTimeline()
}
}
}
@IBAction func firstUnread(_ sender: Any) {
assert(coordinator != nil)
coordinator?.selectFirstUnread()
}
@objc func refreshAccounts(_ sender: Any) {
refreshControl?.endRefreshing()
@@ -292,9 +292,9 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
appDelegate.manualRefresh(errorHandler: ErrorHandler.present(self))
}
}
// MARK: Keyboard shortcuts
@objc func selectNextUp(_ sender: Any?) {
assert(coordinator != nil)
coordinator?.selectPrevArticle()
@@ -309,12 +309,12 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
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()
@@ -331,7 +331,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
}
}
}
func updateNavigationBarTitle(_ text: String) {
if let label = navigationItem.titleView as? UILabel {
label.text = text
@@ -339,7 +339,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
label.sizeToFit()
}
}
func updateNavigationBarSubtitle(_ text: String) {
if let label = navigationItem.subtitleView as? UILabel {
label.text = text
@@ -351,11 +351,11 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
func reinitializeArticles(resetScroll: Bool) {
resetUI(resetScroll: resetScroll)
}
func reloadArticles(animated: Bool) {
applyChanges(animated: animated)
}
func updateArticleSelection(animations: Animations) {
if let article = currentArticle, let indexPath = dataSource.indexPath(for: article) {
if tableView.indexPathForSelectedRow != indexPath {
@@ -364,7 +364,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
} else {
tableView.selectRow(at: nil, animated: animations.contains(.select), scrollPosition: .none)
}
updateUI()
}
@@ -372,7 +372,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
refreshProgressView?.update()
updateToolbar()
}
func hideSearch() {
navigationItem.searchController?.isActive = false
}
@@ -382,11 +382,11 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
navigationItem.searchController?.searchBar.selectedScopeButtonIndex = 1
navigationItem.searchController?.searchBar.becomeFirstResponder()
}
func focus() {
becomeFirstResponder()
}
// MARK: - Table view
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
@@ -397,41 +397,41 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
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] (action, view, completion) in
self?.toggleRead(article)
completion(true)
}
readAction.image = article.status.read ? AppAssets.circleClosedImage : AppAssets.circleOpenImage
readAction.backgroundColor = AppAssets.primaryAccentColor
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] (action, view, completion) in
self?.toggleStar(article)
completion(true)
}
starAction.image = article.status.starred ? AppAssets.starOpenImage : AppAssets.starClosedImage
starAction.backgroundColor = AppAssets.starColor
// 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
@@ -445,11 +445,11 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
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)
}
@@ -468,28 +468,28 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
})
self.present(alert, animated: true)
}
}
moreAction.image = AppAssets.moreImage
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] suggestedActions in
guard let self = self else { return nil }
var menuElements = [UIMenuElement]()
var markActions = [UIAction]()
if let action = self.toggleArticleReadStatusAction(article) {
markActions.append(action)
@@ -502,7 +502,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
markActions.append(action)
}
menuElements.append(UIMenu(title: "", options: .displayInline, children: markActions))
var secondaryActions = [UIAction]()
if let action = self.discloseFeedAction(article) {
secondaryActions.append(action)
@@ -513,7 +513,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
if !secondaryActions.isEmpty {
menuElements.append(UIMenu(title: "", options: .displayInline, children: secondaryActions))
}
var copyActions = [UIAction]()
if let action = self.copyArticleURLAction(article) {
copyActions.append(action)
@@ -524,19 +524,19 @@ 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) {
menuElements.append(UIMenu(title: "", options: .displayInline, children: [action]))
}
return UIMenu(title: "", children: menuElements)
})
}
override func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? {
@@ -544,7 +544,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) else {
return nil
}
let previewView = cell.contentView
let inset: CGFloat = 12
let visibleBounds = previewView.bounds.insetBy(dx: inset, dy: 2)
@@ -554,13 +554,13 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
cornerRadius: 20)
return UITargetedPreview(view: previewView, 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)) else {
return nil
}
let previewView = cell.contentView
let inset: CGFloat = 0
let visibleBounds = previewView.bounds.insetBy(dx: inset, dy: 2)
@@ -568,7 +568,7 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
parameters.backgroundColor = .clear
parameters.visiblePath = UIBezierPath(roundedRect: visibleBounds,
cornerRadius: 20)
return UITargetedPreview(view: previewView, parameters: parameters)
}
@@ -577,17 +577,17 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
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) {
updateUI()
}
@objc func statusesDidChange(_ note: Notification) {
guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set<String>, !articleIDs.isEmpty else {
return
@@ -663,21 +663,21 @@ final class MainTimelineViewController: UITableViewController, UndoableCommandRu
@objc func contentSizeCategoryDidChange(_ note: Notification) {
reloadAllVisibleCells()
}
@objc func displayNameDidChange(_ note: Notification) {
updateNavigationBarTitle(timelineFeed?.nameForDisplay ?? "")
}
@objc func willEnterForeground(_ note: Notification) {
updateUI()
}
@objc func scrollPositionDidChange() {
timelineMiddleIndexPath = tableView.middleVisibleRow()
}
// MARK: Reloading
func queueReloadAvailableCells() {
CoalescingQueue.standard.add(self, #selector(reloadAllVisibleCells))
}
@@ -752,7 +752,7 @@ private extension MainTimelineViewController {
case .alwaysRead:
navigationItem.rightBarButtonItem = nil
}
if isReadArticlesFiltered {
filterButton.style = .prominent
filterButton.tintColor = AppAssets.primaryAccentColor
@@ -771,10 +771,10 @@ private extension MainTimelineViewController {
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
}
}
updateToolbar()
}
func updateToolbar() {
markAllAsReadButton?.isEnabled = isTimelineUnreadAvailable
firstUnreadButton.isEnabled = isTimelineUnreadAvailable
@@ -792,14 +792,14 @@ private extension MainTimelineViewController {
}
}
}
func applyChanges(animated: Bool, completion: (() -> Void)? = nil) {
if (articles?.count ?? 0) == 0 {
tableView.rowHeight = tableView.estimatedRowHeight
} else {
tableView.rowHeight = UITableView.automaticDimension
}
var snapshot = NSDiffableDataSourceSnapshot<Int, Article>()
snapshot.appendSections([0])
snapshot.appendItems(articles ?? ArticleArray(), toSection: 0)
@@ -809,7 +809,7 @@ private extension MainTimelineViewController {
completion?()
}
}
func makeDataSource() -> UITableViewDiffableDataSource<Int, Article> {
let dataSource: UITableViewDiffableDataSource<Int, Article> =
MainTimelineDataSource(tableView: tableView, cellProvider: { [weak self] tableView, indexPath, article in
@@ -823,12 +823,12 @@ private extension MainTimelineViewController {
cell.cellData = cellData
return cell
}
})
dataSource.defaultRowAnimation = .middle
return dataSource
}
@discardableResult
func configure(article: Article) -> MainTimelineCellData {
let iconImage = iconImageFor(article)
@@ -837,7 +837,7 @@ private extension MainTimelineViewController {
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
@@ -852,7 +852,7 @@ private extension MainTimelineViewController {
func toggleArticleReadStatusAction(_ article: Article) -> UIAction? {
guard !article.status.read || article.isAvailableToMarkUnread else { return nil }
let title = article.status.read ?
NSLocalizedString("Mark as Unread", comment: "Mark as Unread") :
NSLocalizedString("Mark as Read", comment: "Mark as Read")
@@ -861,10 +861,10 @@ private extension MainTimelineViewController {
let action = UIAction(title: title, image: image) { [weak self] action in
self?.toggleRead(article)
}
return action
}
func toggleStar(_ article: Article) {
assert(coordinator != nil)
coordinator?.toggleStar(article)
@@ -880,7 +880,7 @@ private extension MainTimelineViewController {
let action = UIAction(title: title, image: image) { [weak self] action in
self?.toggleStar(article)
}
return action
}
@@ -933,7 +933,7 @@ private extension MainTimelineViewController {
}
return action
}
func markAboveAsReadAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? {
guard canMarkAboveAsRead(for: article), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else {
return nil
@@ -962,7 +962,7 @@ private extension MainTimelineViewController {
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?.markBelowAsRead(article)
@@ -992,7 +992,7 @@ private extension MainTimelineViewController {
}
return action
}
func discloseFeedAlertAction(_ article: Article, completion: @escaping (Bool) -> Void) -> UIAlertAction? {
guard let feed = article.feed,
!timelineFeedIsEqualTo(feed) else { return nil }
@@ -1020,11 +1020,11 @@ private extension MainTimelineViewController {
guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else {
return nil
}
let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Command")
let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String
let action = UIAction(title: title, image: AppAssets.markAllAsReadImage) { [weak self] action in
MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView) { [weak self] in
self?.markAllAsRead(articles)
@@ -1038,18 +1038,18 @@ private extension MainTimelineViewController {
guard let fetchedArticles = try? feed.fetchArticles() else {
return nil
}
let articles = Array(fetchedArticles)
guard articles.canMarkAllAsRead(), let contentView = self.tableView.cellForRow(at: indexPath)?.contentView else {
return nil
}
let localizedMenuText = NSLocalizedString("Mark All as Read in “%@”", comment: "Mark All as Read in Feed")
let title = NSString.localizedStringWithFormat(localizedMenuText as NSString, feed.nameForDisplay) as String
let cancel = {
completion(true)
}
let action = UIAlertAction(title: title, style: .default) { [weak self] action in
MarkAsReadAlertController.confirm(self, coordinator: self?.coordinator, confirmTitle: title, sourceType: contentView, cancelCompletion: cancel) { [weak self] in
self?.markAllAsRead(articles)
@@ -1058,7 +1058,7 @@ private extension MainTimelineViewController {
}
return action
}
func copyArticleURLAction(_ article: Article) -> UIAction? {
guard let url = article.preferredURL else { return nil }
let title = NSLocalizedString("Copy Article URL", comment: "Copy Article URL")
@@ -1067,7 +1067,7 @@ private extension MainTimelineViewController {
}
return action
}
func copyExternalURLAction(_ article: Article) -> UIAction? {
guard let externalLink = article.externalLink, externalLink != article.preferredLink, let url = URL(string: externalLink) else { return nil }
let title = NSLocalizedString("Copy External URL", comment: "Copy External URL")
@@ -1101,18 +1101,18 @@ private extension MainTimelineViewController {
}
return action
}
func shareDialogForTableCell(indexPath: IndexPath, url: URL, title: String?) {
let activityViewController = UIActivityViewController(url: url, title: title, applicationActivities: nil)
guard let cell = tableView.cellForRow(at: indexPath) else { return }
let popoverController = activityViewController.popoverPresentationController
popoverController?.sourceView = cell
popoverController?.sourceRect = CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height)
present(activityViewController, animated: true)
}
func shareAction(_ article: Article, indexPath: IndexPath) -> UIAction? {
guard let url = article.preferredURL else { return nil }
let title = NSLocalizedString("Share", comment: "Share")
@@ -1121,7 +1121,7 @@ private extension MainTimelineViewController {
}
return action
}
func shareAlertAction(_ article: Article, indexPath: IndexPath, completion: @escaping (Bool) -> Void) -> UIAlertAction? {
guard let url = article.preferredURL else { return nil }
let title = NSLocalizedString("Share", comment: "Share")
@@ -1131,5 +1131,5 @@ private extension MainTimelineViewController {
}
return action
}
}
@@ -16,19 +16,19 @@ extension UIBarButtonItem: MarkAsReadAlertControllerSourceType {}
struct MarkAsReadAlertController {
static func confirm<T>(_ controller: UIViewController?,
coordinator: SceneCoordinator?,
confirmTitle: String,
sourceType: T,
cancelCompletion: (() -> Void)? = nil,
completion: @escaping () -> Void) where T: MarkAsReadAlertControllerSourceType {
guard let controller = controller, let coordinator = coordinator else {
completion()
return
}
if AppDefaults.shared.confirmMarkAllAsRead {
let alertController = MarkAsReadAlertController.alert(coordinator: coordinator, confirmTitle: confirmTitle, cancelCompletion: cancelCompletion, sourceType: sourceType) { _ in
completion()
@@ -38,20 +38,20 @@ struct MarkAsReadAlertController {
completion()
}
}
private static func alert<T>(coordinator: SceneCoordinator,
confirmTitle: String,
cancelCompletion: (() -> Void)?,
sourceType: T,
completion: @escaping (UIAlertAction) -> Void) -> UIAlertController where T: MarkAsReadAlertControllerSourceType {
let title = NSLocalizedString("Mark As Read", comment: "Mark As Read")
let message = NSLocalizedString("You can turn this confirmation off in Settings.",
comment: "You can turn this confirmation off in Settings.")
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
let settingsTitle = NSLocalizedString("Open Settings", comment: "Open Settings")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { _ in
cancelCompletion?()
@@ -60,24 +60,24 @@ struct MarkAsReadAlertController {
coordinator.showSettings(scrollToArticlesSection: true)
}
let markAction = UIAlertAction(title: confirmTitle, style: .default, handler: completion)
alertController.addAction(markAction)
alertController.addAction(settingsAction)
alertController.addAction(cancelAction)
if let barButtonItem = sourceType as? UIBarButtonItem {
alertController.popoverPresentationController?.barButtonItem = barButtonItem
}
if let rect = sourceType as? CGRect {
alertController.popoverPresentationController?.sourceRect = rect
}
if let view = sourceType as? UIView {
alertController.popoverPresentationController?.sourceView = view
}
return alertController
}
}
+26 -26
View File
@@ -10,28 +10,28 @@ import UIKit
import Account
final class RootSplitViewController: UISplitViewController {
var coordinator: SceneCoordinator!
override var prefersStatusBarHidden: Bool {
return coordinator.prefersStatusBarHidden
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
override func viewDidAppear(_ animated: Bool) {
coordinator.resetFocus()
}
override func show(_ column: UISplitViewController.Column) {
guard !coordinator.isNavigationDisabled else { return }
super.show(column)
}
// MARK: Keyboard Shortcuts
@objc func scrollOrGoToNextUnread(_ sender: Any?) {
coordinator.scrollOrGoToNextUnread()
}
@@ -39,24 +39,24 @@ final class RootSplitViewController: UISplitViewController {
@objc func scrollUp(_ sender: Any?) {
coordinator.scrollUp()
}
@objc func goToPreviousUnread(_ sender: Any?) {
coordinator.selectPrevUnread()
}
@objc func nextUnread(_ sender: Any?) {
coordinator.selectNextUnread()
}
@objc func markRead(_ sender: Any?) {
coordinator.markAsReadForCurrentArticle()
}
@objc func markUnreadAndGoToNextUnread(_ sender: Any?) {
coordinator.markAsUnreadForCurrentArticle()
coordinator.selectNextUnread()
}
@objc func markAllAsReadAndGoToNextUnread(_ sender: Any?) {
coordinator.markAllAsReadInTimeline() {
self.coordinator.selectNextUnread()
@@ -66,23 +66,23 @@ final class RootSplitViewController: UISplitViewController {
@objc func markAboveAsRead(_ sender: Any?) {
coordinator.markAboveAsRead()
}
@objc func markBelowAsRead(_ sender: Any?) {
coordinator.markBelowAsRead()
}
@objc func markUnread(_ sender: Any?) {
coordinator.markAsUnreadForCurrentArticle()
}
@objc func goToPreviousSubscription(_ sender: Any?) {
coordinator.selectPrevFeed()
}
@objc func goToNextSubscription(_ sender: Any?) {
coordinator.selectNextFeed()
}
@objc func openInBrowser(_ sender: Any?) {
coordinator.showBrowserForCurrentArticle()
}
@@ -90,11 +90,11 @@ final class RootSplitViewController: UISplitViewController {
@objc func openInAppBrowser(_ sender: Any?) {
coordinator.showInAppBrowser()
}
@objc func articleSearch(_ sender: Any?) {
coordinator.showSearch()
}
@objc func addNewFeed(_ sender: Any?) {
coordinator.showAddFeed()
}
@@ -106,27 +106,27 @@ final class RootSplitViewController: UISplitViewController {
@objc func cleanUp(_ sender: Any?) {
coordinator.cleanUp(conditional: false)
}
@objc func toggleReadFeedsFilter(_ sender: Any?) {
coordinator.toggleReadFeedsFilter()
}
@objc func toggleReadArticlesFilter(_ sender: Any?) {
coordinator.toggleReadArticlesFilter()
}
@objc func refresh(_ sender: Any?) {
appDelegate.manualRefresh(errorHandler: ErrorHandler.present(self))
}
@objc func goToToday(_ sender: Any?) {
coordinator.selectTodayFeed()
}
@objc func goToAllUnread(_ sender: Any?) {
coordinator.selectAllUnreadFeed()
}
@objc func goToStarred(_ sender: Any?) {
coordinator.selectStarredFeed()
}
@@ -138,7 +138,7 @@ final class RootSplitViewController: UISplitViewController {
@objc func toggleRead(_ sender: Any?) {
coordinator.toggleReadForCurrentArticle()
}
@objc func toggleStarred(_ sender: Any?) {
coordinator.toggleStarredForCurrentArticle()
}
+274 -274
View File
File diff suppressed because it is too large. Load diff
+34 -34
View File
@@ -11,16 +11,16 @@ import UserNotifications
import Account
final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var coordinator: SceneCoordinator!
// UIWindowScene delegate
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
window!.tintColor = AppAssets.primaryAccentColor
let rootViewController = window!.rootViewController as! RootSplitViewController
rootViewController.presentsWithGesture = true
rootViewController.showsSecondaryOnlyButton = true
@@ -36,7 +36,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
coordinator = SceneCoordinator(rootSplitViewController: rootViewController)
rootViewController.coordinator = coordinator
rootViewController.delegate = coordinator
coordinator.restoreWindowState(session.stateRestorationActivity)
updateUserInterfaceStyle()
@@ -47,34 +47,34 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
self.scene(scene, openURLContexts: connectionOptions.urlContexts)
return
}
if let shortcutItem = connectionOptions.shortcutItem {
handleShortcutItem(shortcutItem)
return
}
if let notificationResponse = connectionOptions.notificationResponse {
coordinator.handle(notificationResponse)
return
}
if let userActivity = connectionOptions.userActivities.first ?? session.stateRestorationActivity {
coordinator.handle(userActivity)
}
}
func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
appDelegate.resumeDatabaseProcessingIfNecessary()
handleShortcutItem(shortcutItem)
completionHandler(true)
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
appDelegate.resumeDatabaseProcessingIfNecessary()
coordinator.handle(userActivity)
}
func sceneDidEnterBackground(_ scene: UIScene) {
ArticleStringFormatter.emptyCaches()
appDelegate.prepareAccountsForBackground()
@@ -85,39 +85,39 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
appDelegate.prepareAccountsForForeground()
coordinator.resetFocus()
}
func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? {
return coordinator.stateRestorationActivity
}
// API
func handle(_ response: UNNotificationResponse) {
appDelegate.resumeDatabaseProcessingIfNecessary()
coordinator.handle(response)
}
func suspend() {
coordinator.suspend()
}
func cleanUp(conditional: Bool) {
coordinator.cleanUp(conditional: conditional)
}
// Handle Opening of URLs
func scene(_ scene: UIScene, openURLContexts urlContexts: Set<UIOpenURLContext>) {
guard let context = urlContexts.first else { return }
DispatchQueue.main.async {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.coordinator.dismissIfLaunchingFromExternalAction()
}
let urlString = context.url.absoluteString
// Handle the feed: and feeds: schemes
if urlString.starts(with: "feed:") || urlString.starts(with: "feeds:") {
let normalizedURLString = urlString.normalizedURL
@@ -125,7 +125,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
self.coordinator.showAddFeed(initialFeed: normalizedURLString, initialFeedName: nil)
}
}
// Show Unread View or Article
if urlString.contains(WidgetDeepLink.unread.url.absoluteString) {
guard let comps = URLComponents(string: urlString ) else { return }
@@ -141,7 +141,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
self.coordinator.selectAllUnreadFeed()
}
}
// Show Today View or Article
if urlString.contains(WidgetDeepLink.today.url.absoluteString) {
guard let comps = URLComponents(string: urlString ) else { return }
@@ -157,7 +157,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
self.coordinator.selectTodayFeed()
}
}
// Show Starred View or Article
if urlString.contains(WidgetDeepLink.starred.url.absoluteString) {
guard let comps = URLComponents(string: urlString ) else { return }
@@ -173,31 +173,31 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
self.coordinator.selectStarredFeed()
}
}
let filename = context.url.standardizedFileURL.path
if filename.hasSuffix(ArticleTheme.nnwThemeSuffix) {
self.coordinator.importTheme(filename: filename)
return
}
// Handle theme URLs: netnewswire://theme/add?url={url}
guard let comps = URLComponents(url: context.url, resolvingAgainstBaseURL: false),
"theme" == comps.host,
let queryItems = comps.queryItems else {
return
}
if let providedThemeURL = queryItems.first(where: { $0.name == "url" })?.value {
if let themeURL = URL(string: providedThemeURL) {
let request = URLRequest(url: themeURL)
DispatchQueue.main.async {
NotificationCenter.default.post(name: .didBeginDownloadingTheme, object: nil)
}
let task = URLSession.shared.downloadTask(with: request) { location, response, error in
guard
let location = location else { return }
do {
try ArticleThemeDownloader.shared.handleFile(at: location)
} catch {
@@ -212,14 +212,14 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
} else {
return
}
}
}
}
private extension SceneDelegate {
func handleShortcutItem(_ shortcutItem: UIApplicationShortcutItem) {
switch shortcutItem.type {
case "com.ranchero.NetNewsWire.FirstUnread":
+7 -7
View File
@@ -15,11 +15,11 @@ final class AboutViewController: UITableViewController {
@IBOutlet weak var acknowledgmentsTextView: UITextView!
@IBOutlet weak var thanksTextView: UITextView!
@IBOutlet weak var dedicationTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
configureCell(file: "About", textView: aboutTextView)
configureCell(file: "Credits", textView: creditsTextView)
configureCell(file: "Thanks", textView: thanksTextView)
@@ -32,7 +32,7 @@ final class AboutViewController: UITableViewController {
buildLabel.numberOfLines = 0
buildLabel.sizeToFit()
buildLabel.translatesAutoresizingMaskIntoConstraints = false
let wrapperView = UIView(frame: CGRect(x: 0, y: 0, width: buildLabel.frame.width, height: buildLabel.frame.height + 10.0))
wrapperView.translatesAutoresizingMaskIntoConstraints = false
wrapperView.addSubview(buildLabel)
@@ -42,11 +42,11 @@ final class AboutViewController: UITableViewController {
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
private extension AboutViewController {
func configureCell(file: String, textView: UITextView) {
let url = Bundle.main.url(forResource: file, withExtension: "rtf")!
let string = try! NSAttributedString(url: url, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
@@ -55,5 +55,5 @@ private extension AboutViewController {
textView.adjustsFontForContentSizeCategory = true
textView.font = .preferredFont(forTextStyle: .body)
}
}
+20 -20
View File
@@ -21,7 +21,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
case icloud
case web
case selfhosted
var sectionHeader: String {
switch self {
case .local:
@@ -34,7 +34,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
return NSLocalizedString("Self-hosted", comment: "Self hosted Account")
}
}
var sectionFooter: String {
switch self {
case .local:
@@ -47,7 +47,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
return NSLocalizedString("Self-hosted accounts sync your feeds across all your devices", comment: "Self hosted Account")
}
}
var sectionContent: [AccountType] {
switch self {
case .local:
@@ -65,7 +65,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
@@ -73,27 +73,27 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
override func numberOfSections(in tableView: UITableView) -> Int {
return AddAccountSections.allCases.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == AddAccountSections.local.rawValue {
return AddAccountSections.local.sectionContent.count
}
if section == AddAccountSections.icloud.rawValue {
return AddAccountSections.icloud.sectionContent.count
}
if section == AddAccountSections.web.rawValue {
return AddAccountSections.web.sectionContent.count
}
if section == AddAccountSections.selfhosted.rawValue {
return AddAccountSections.selfhosted.sectionContent.count
}
return 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case AddAccountSections.local.rawValue:
@@ -108,7 +108,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
return nil
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch section {
case AddAccountSections.local.rawValue:
@@ -123,10 +123,10 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
return nil
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SettingsAccountTableViewCell", for: indexPath) as! SettingsComboTableViewCell
switch indexPath.section {
case AddAccountSections.local.rawValue:
cell.comboNameLabel?.text = AddAccountSections.local.sectionContent[indexPath.row].localizedAccountName()
@@ -149,15 +149,15 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
case AddAccountSections.selfhosted.rawValue:
cell.comboNameLabel?.text = AddAccountSections.selfhosted.sectionContent[indexPath.row].localizedAccountName()
cell.comboImage?.image = AppAssets.image(for: AddAccountSections.selfhosted.sectionContent[indexPath.row])
default:
return cell
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case AddAccountSections.local.rawValue:
let type = AddAccountSections.local.sectionContent[indexPath.row]
@@ -175,7 +175,7 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
return
}
}
private func presentController(for accountType: AccountType) {
switch accountType {
case .onMyMac:
@@ -216,15 +216,15 @@ final class AddAccountViewController: UITableViewController, AddAccountDismissDe
present(navController, animated: true)
}
}
func dismiss() {
navigationController?.popViewController(animated: false)
}
}
extension AddAccountViewController: OAuthAccountAuthorizationOperationDelegate {
func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didCreate account: Account) {
let rootViewController = view.window?.rootViewController
@@ -241,7 +241,7 @@ extension AddAccountViewController: OAuthAccountAuthorizationOperationDelegate {
dismiss()
}
func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didFailWith error: Error) {
presentError(error)
}
+11 -11
View File
@@ -9,7 +9,7 @@
import UIKit
struct ArticleThemeImporter {
static func importTheme(controller: UIViewController, url: URL) throws {
let theme = try ArticleTheme(url: url, isAppTheme: false)
@@ -20,10 +20,10 @@ struct ArticleThemeImporter {
let message = NSString.localizedStringWithFormat(localizedMessageText as NSString, theme.creatorHomePage) as String
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel))
if let websiteURL = URL(string: theme.creatorHomePage) {
let visitSiteTitle = NSLocalizedString("Show Website", comment: "Show Website")
let visitSiteAction = UIAlertAction(title: visitSiteTitle, style: .default) { action in
@@ -71,32 +71,32 @@ struct ArticleThemeImporter {
} else {
importTheme()
}
}
alertController.addAction(installThemeAction)
alertController.preferredAction = installThemeAction
controller.present(alertController, animated: true)
}
}
private extension ArticleThemeImporter {
static func confirmImportSuccess(controller: UIViewController, themeName: String) {
let title = NSLocalizedString("Theme installed", comment: "Theme installed")
let localizedMessageText = NSLocalizedString("The theme “%@” has been installed.", comment: "Theme installed")
let message = NSString.localizedStringWithFormat(localizedMessageText as NSString, themeName) as String
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let doneTitle = NSLocalizedString("Done", comment: "Done")
alertController.addAction(UIAlertAction(title: doneTitle, style: .default))
controller.present(alertController, animated: true)
}
}
@@ -20,12 +20,12 @@ final class ArticleThemesTableViewController: UITableViewController {
let importBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(importTheme(_:)));
importBarButtonItem.title = NSLocalizedString("Import Theme", comment: "Import Theme");
navigationItem.rightBarButtonItem = importBarButtonItem
NotificationCenter.default.addObserver(self, selector: #selector(articleThemeNamesDidChangeNotification(_:)), name: .ArticleThemeNamesDidChangeNotification, object: nil)
}
// MARK: Notifications
@objc func articleThemeNamesDidChangeNotification(_ note: Notification) {
tableView.reloadData()
}
@@ -49,21 +49,21 @@ final class ArticleThemesTableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let themeName: String
if indexPath.row == 0 {
themeName = ArticleTheme.defaultTheme.name
} else {
themeName = ArticleThemesManager.shared.themeNames[indexPath.row - 1]
}
cell.textLabel?.text = themeName
if themeName == ArticleThemesManager.shared.currentTheme.name {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
@@ -82,12 +82,12 @@ final class ArticleThemesTableViewController: UITableViewController {
let deleteTitle = NSLocalizedString("Delete", comment: "Delete")
let deleteAction = UIContextualAction(style: .normal, title: deleteTitle) { [weak self] (action, view, completion) in
let title = NSLocalizedString("Delete Theme?", comment: "Delete Theme")
let localizedMessageText = NSLocalizedString("Are you sure you want to delete the theme “%@”?.", comment: "Delete Theme Message")
let message = NSString.localizedStringWithFormat(localizedMessageText as NSString, themeName) as String
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { action in
completion(true)
@@ -100,13 +100,13 @@ final class ArticleThemesTableViewController: UITableViewController {
completion(true)
}
alertController.addAction(deleteAction)
self?.present(alertController, animated: true)
}
deleteAction.image = AppAssets.trashImage
deleteAction.backgroundColor = UIColor.systemRed
return UISwipeActionsConfiguration(actions: [deleteAction])
}
}
@@ -114,12 +114,12 @@ final class ArticleThemesTableViewController: UITableViewController {
// MARK: UIDocumentPickerDelegate
extension ArticleThemesTableViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let url = urls.first else { return }
if url.startAccessingSecurityScopedResource() {
defer {
url.stopAccessingSecurityScopedResource()
}
@@ -11,7 +11,7 @@ import Articles
class ModernTimelineCustomizerTableViewController: UITableViewController {
private var previewArticle: Article {
var components = DateComponents()
components.year = 1925
@@ -20,7 +20,7 @@ class ModernTimelineCustomizerTableViewController: UITableViewController {
let calendar = Calendar.current
let date = calendar.date(from: components)!
return Article(accountID: "_testID",
articleID: "_testArticleID",
feedID: "_testFeedID",
@@ -38,16 +38,16 @@ class ModernTimelineCustomizerTableViewController: UITableViewController {
authors: Set([Author(authorID: "_testAuthorID", name: "F. Scott Fitzgerald", url: nil, avatarURL: nil, emailAddress: nil)!]),
status: ArticleStatus(articleID: "_testArticleID", read: false, starred: false, dateArrived: .now))
}
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Timeline Customizer", comment: "Timeline Customizer")
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
tableView.reloadSections(IndexSet(integer: 2), with: .fade)
}
@@ -61,7 +61,7 @@ class ModernTimelineCustomizerTableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 { return NSLocalizedString("Icon Size", comment: "Icon Size")}
if section == 1 { return NSLocalizedString("Number of Lines", comment: "Number of Lines")}
@@ -70,21 +70,21 @@ class ModernTimelineCustomizerTableViewController: UITableViewController {
return nil
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "IconSizeCell") as! ModernTimelineSliderCell
cell.sliderConfiguration = .iconSize
return cell
}
if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "NumberOfLinesCell") as! ModernTimelineSliderCell
cell.sliderConfiguration = .numberOfLines
return cell
}
if indexPath.section == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTimelineIconFeedCell") as? MainTimelineIconFeedCell ?? MainTimelineIconFeedCell()
cell.cellData = MainTimelineCellData(article: previewArticle,
@@ -98,7 +98,7 @@ class ModernTimelineCustomizerTableViewController: UITableViewController {
cell.isPreview = true
return cell
}
if indexPath.section == 3 {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTimelineFeedCell") as? MainTimelineFeedCell ?? MainTimelineFeedCell()
cell.cellData = MainTimelineCellData(article: previewArticle,
@@ -112,11 +112,11 @@ class ModernTimelineCustomizerTableViewController: UITableViewController {
cell.isPreview = true
return cell
}
return UITableViewCell()
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return nil
}
@@ -124,7 +124,7 @@ class ModernTimelineCustomizerTableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
// MARK: - Notifications
@objc func userDefaultsDidChange(_ note: Notification) {
tableView.reloadSections(IndexSet(integersIn: 2...3), with: .none)
+15 -15
View File
@@ -14,35 +14,35 @@ enum SliderConfiguration {
}
class ModernTimelineSliderCell: UITableViewCell {
@IBOutlet weak var slider: UISlider!
private let container = UIView()
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
container.layer.cornerRadius = contentView.frame.height/2
container.backgroundColor = .systemBackground
container.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(container)
contentView.sendSubviewToBack(container)
NSLayoutConstraint.activate([
container.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0),
container.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0),
@@ -51,7 +51,7 @@ class ModernTimelineSliderCell: UITableViewCell {
])
contentView.backgroundColor = .systemGroupedBackground
}
var sliderConfiguration: SliderConfiguration! {
didSet {
switch sliderConfiguration {
@@ -70,14 +70,14 @@ class ModernTimelineSliderCell: UITableViewCell {
}
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func sliderValueChanges(_ sender: Any) {
switch sliderConfiguration {
case .numberOfLines:
@@ -89,5 +89,5 @@ class ModernTimelineSliderCell: UITableViewCell {
return
}
}
}
@@ -16,7 +16,7 @@ final class SettingsComboTableViewCell: VibrantTableViewCell {
override func updateVibrancy(animated: Bool) {
super.updateVibrancy(animated: animated)
updateLabelVibrancy(comboNameLabel, color: labelColor, animated: animated)
let tintColor = isHighlighted || isSelected ? AppAssets.vibrantTextColor : UIColor.label
if animated {
UIView.animate(withDuration: Self.duration) {
@@ -26,5 +26,5 @@ final class SettingsComboTableViewCell: VibrantTableViewCell {
self.comboImage?.tintColor = tintColor
}
}
}
+50 -50
View File
@@ -16,7 +16,7 @@ import UniformTypeIdentifiers
final class SettingsViewController: UITableViewController {
private weak var opmlAccount: Account?
@IBOutlet weak var timelineSortOrderSwitch: UISwitch!
@IBOutlet weak var groupByFeedSwitch: UISwitch!
@IBOutlet weak var refreshClearsReadArticlesSwitch: UISwitch!
@@ -26,10 +26,10 @@ final class SettingsViewController: UITableViewController {
@IBOutlet weak var colorPaletteDetailLabel: UILabel!
@IBOutlet weak var openLinksInNetNewsWire: UISwitch!
@IBOutlet weak var enableJavaScriptSwitch: UISwitch!
var scrollToArticlesSection = false
weak var presentingParentController: UIViewController?
override func viewDidLoad() {
// This hack mostly works around a bug in static tables with dynamic type. See: https://spin.atomicobject.com/2018/10/15/dynamic-type-static-uitableview/
NotificationCenter.default.removeObserver(tableView!, name: UIContentSizeCategory.didChangeNotification, object: nil)
@@ -41,14 +41,14 @@ final class SettingsViewController: UITableViewController {
tableView.register(UINib(nibName: "SettingsComboTableViewCell", bundle: nil), forCellReuseIdentifier: "SettingsComboTableViewCell")
tableView.register(UINib(nibName: "SettingsTableViewCell", bundle: nil), forCellReuseIdentifier: "SettingsTableViewCell")
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if AppDefaults.shared.timelineSortDirection == .orderedAscending {
timelineSortOrderSwitch.isOn = true
} else {
@@ -67,7 +67,7 @@ final class SettingsViewController: UITableViewController {
refreshClearsReadArticlesSwitch.isOn = false
}
articleThemeDetailLabel.text = ArticleThemesManager.shared.currentTheme.name
if AppDefaults.shared.confirmMarkAllAsRead {
@@ -81,17 +81,17 @@ final class SettingsViewController: UITableViewController {
} else {
showFullscreenArticlesSwitch.isOn = false
}
if AppDefaults.shared.isArticleContentJavascriptEnabled {
enableJavaScriptSwitch.isOn = true
} else {
enableJavaScriptSwitch.isOn = false
}
colorPaletteDetailLabel.text = String(describing: AppDefaults.userInterfaceColorPalette)
openLinksInNetNewsWire.isOn = !AppDefaults.shared.useSystemBrowser
let buildLabel = NonIntrinsicLabel(frame: CGRect(x: 32.0, y: 0.0, width: 0.0, height: 0.0))
buildLabel.font = UIFont.systemFont(ofSize: 11.0)
@@ -99,27 +99,27 @@ final class SettingsViewController: UITableViewController {
buildLabel.text = "\(Bundle.main.appName) \(Bundle.main.versionNumber) (Build \(Bundle.main.buildNumber))"
buildLabel.sizeToFit()
buildLabel.translatesAutoresizingMaskIntoConstraints = false
let wrapperView = UIView(frame: CGRect(x: 0, y: 0, width: buildLabel.frame.width, height: buildLabel.frame.height + 10.0))
wrapperView.translatesAutoresizingMaskIntoConstraints = false
wrapperView.addSubview(buildLabel)
tableView.tableFooterView = wrapperView
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
if scrollToArticlesSection {
tableView.scrollToRow(at: IndexPath(row: 0, section: 4), at: .top, animated: true)
scrollToArticlesSection = false
}
}
// MARK: UITableView
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
@@ -244,7 +244,7 @@ final class SettingsViewController: UITableViewController {
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return false
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return false
}
@@ -252,21 +252,21 @@ final class SettingsViewController: UITableViewController {
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
return super.tableView(tableView, indentationLevelForRowAt: IndexPath(row: 0, section: 1))
}
// MARK: Actions
@IBAction func done(_ sender: Any) {
dismiss(animated: true)
}
@IBAction func switchTimelineOrder(_ sender: Any) {
if timelineSortOrderSwitch.isOn {
AppDefaults.shared.timelineSortDirection = .orderedAscending
@@ -274,7 +274,7 @@ final class SettingsViewController: UITableViewController {
AppDefaults.shared.timelineSortDirection = .orderedDescending
}
}
@IBAction func switchGroupByFeed(_ sender: Any) {
if groupByFeedSwitch.isOn {
AppDefaults.shared.timelineGroupByFeed = true
@@ -282,7 +282,7 @@ final class SettingsViewController: UITableViewController {
AppDefaults.shared.timelineGroupByFeed = false
}
}
@IBAction func switchClearsReadArticles(_ sender: Any) {
if refreshClearsReadArticlesSwitch.isOn {
AppDefaults.shared.refreshClearsReadArticles = true
@@ -290,7 +290,7 @@ final class SettingsViewController: UITableViewController {
AppDefaults.shared.refreshClearsReadArticles = false
}
}
@IBAction func switchConfirmMarkAllAsRead(_ sender: Any) {
if confirmMarkAllAsReadSwitch.isOn {
AppDefaults.shared.confirmMarkAllAsRead = true
@@ -298,7 +298,7 @@ final class SettingsViewController: UITableViewController {
AppDefaults.shared.confirmMarkAllAsRead = false
}
}
@IBAction func switchFullscreenArticles(_ sender: Any) {
if showFullscreenArticlesSwitch.isOn {
AppDefaults.shared.articleFullscreenAvailable = true
@@ -306,7 +306,7 @@ final class SettingsViewController: UITableViewController {
AppDefaults.shared.articleFullscreenAvailable = false
}
}
@IBAction func switchBrowserPreference(_ sender: Any) {
if openLinksInNetNewsWire.isOn {
AppDefaults.shared.useSystemBrowser = false
@@ -314,18 +314,18 @@ final class SettingsViewController: UITableViewController {
AppDefaults.shared.useSystemBrowser = true
}
}
@IBAction func switchJavaScriptPreference(_ sender: Any) {
AppDefaults.shared.isArticleContentJavascriptEnabled = enableJavaScriptSwitch.isOn
}
// MARK: Notifications
@objc func contentSizeCategoryDidChange() {
tableView.reloadData()
}
@objc func accountsDidChange() {
tableView.reloadData()
}
@@ -333,17 +333,17 @@ final class SettingsViewController: UITableViewController {
@objc func displayNameDidChange() {
tableView.reloadData()
}
@objc func browserPreferenceDidChange() {
tableView.reloadData()
}
}
// MARK: OPML Document Picker
extension SettingsViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
for url in urls {
opmlAccount?.importOPML(url) { result in
@@ -358,13 +358,13 @@ extension SettingsViewController: UIDocumentPickerDelegate {
}
}
}
}
// MARK: Private
private extension SettingsViewController {
func addFeed() {
self.dismiss(animated: true)
@@ -374,10 +374,10 @@ private extension SettingsViewController {
addViewController.initialFeedName = NSLocalizedString("NetNewsWire News", comment: "NetNewsWire News")
addNavViewController.modalPresentationStyle = .formSheet
addNavViewController.preferredContentSize = AddFeedViewController.preferredContentSizeForFormSheetDisplay
presentingParentController?.present(addNavViewController, animated: true)
}
func importOPML(sourceView: UIView, sourceRect: CGRect) {
switch AccountManager.shared.activeAccounts.count {
case 0:
@@ -389,11 +389,11 @@ private extension SettingsViewController {
importOPMLAccountPicker(sourceView: sourceView, sourceRect: sourceRect)
}
}
func importOPMLAccountPicker(sourceView: UIView, sourceRect: CGRect) {
let title = NSLocalizedString("Choose an account to receive the imported feeds and folders", comment: "Import Account")
let alert = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
if let popoverController = alert.popoverPresentationController {
popoverController.sourceView = view
popoverController.sourceRect = sourceRect
@@ -412,15 +412,15 @@ private extension SettingsViewController {
self.present(alert, animated: true)
}
func importOPMLDocumentPicker() {
let docPicker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.opml, UTType.xml], asCopy: true)
docPicker.delegate = self
docPicker.modalPresentationStyle = .formSheet
self.present(docPicker, animated: true)
}
func exportOPML(sourceView: UIView, sourceRect: CGRect) {
if AccountManager.shared.accounts.count == 1 {
opmlAccount = AccountManager.shared.accounts.first!
@@ -429,11 +429,11 @@ private extension SettingsViewController {
exportOPMLAccountPicker(sourceView: sourceView, sourceRect: sourceRect)
}
}
func exportOPMLAccountPicker(sourceView: UIView, sourceRect: CGRect) {
let title = NSLocalizedString("Choose an account with the subscriptions to export", comment: "Export Account")
let alert = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
if let popoverController = alert.popoverPresentationController {
popoverController.sourceView = view
popoverController.sourceRect = sourceRect
@@ -452,10 +452,10 @@ private extension SettingsViewController {
self.present(alert, animated: true)
}
func exportOPMLDocumentPicker() {
guard let account = opmlAccount else { return }
let accountName = account.nameForDisplay.replacingOccurrences(of: " ", with: "").trimmingCharacters(in: .whitespaces)
let filename = "Subscriptions-\(accountName).opml"
let tempFile = FileManager.default.temporaryDirectory.appendingPathComponent(filename)
@@ -465,12 +465,12 @@ private extension SettingsViewController {
} catch {
self.presentError(title: "OPML Export Error", message: error.localizedDescription)
}
let docPicker = UIDocumentPickerViewController(forExporting: [tempFile])
docPicker.modalPresentationStyle = .formSheet
self.present(docPicker, animated: true)
}
func openURL(_ urlString: String) {
let vc = SFSafariViewController(url: URL(string: urlString)!)
vc.modalPresentationStyle = .pageSheet
@@ -9,7 +9,7 @@
import UIKit
final class ShareFolderPickerCell: UITableViewCell {
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var label: UILabel!
}
@@ -20,13 +20,13 @@ final class ShareFolderPickerController: UITableViewController {
var selectedContainerID: ContainerIdentifier?
weak var delegate: ShareFolderPickerControllerDelegate?
override func viewDidLoad() {
tableView.register(UINib(nibName: "ShareFolderPickerAccountCell", bundle: Bundle.main), forCellReuseIdentifier: "AccountCell")
tableView.register(UINib(nibName: "ShareFolderPickerFolderCell", bundle: Bundle.main), forCellReuseIdentifier: "FolderCell")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
@@ -34,7 +34,7 @@ final class ShareFolderPickerController: UITableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return containers?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let container = containers?[indexPath.row]
let cell: ShareFolderPickerCell = {
@@ -44,7 +44,7 @@ final class ShareFolderPickerController: UITableViewController {
return tableView.dequeueReusableCell(withIdentifier: "FolderCell", for: indexPath) as! ShareFolderPickerCell
}
}()
if let account = container as? ExtensionAccount {
cell.icon.image = AppAssets.image(for: account.type)
} else {
@@ -58,13 +58,13 @@ final class ShareFolderPickerController: UITableViewController {
} else {
cell.accessoryType = .none
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let container = containers?[indexPath.row] else { return }
if let account = container as? ExtensionAccount, account.disallowFeedInRootFolder {
tableView.selectRow(at: nil, animated: false, scrollPosition: .none)
} else {
@@ -73,5 +73,5 @@ final class ShareFolderPickerController: UITableViewController {
delegate?.shareFolderPickerDidSelect(container)
}
}
}
+21 -21
View File
@@ -15,15 +15,15 @@ import RSTree
import UniformTypeIdentifiers
final class ShareViewController: SLComposeServiceViewController, ShareFolderPickerControllerDelegate {
private var url: URL?
private var extensionContainers: ExtensionContainers?
private var flattenedContainers: [ExtensionContainer]!
private var selectedContainer: ExtensionContainer?
private var folderItem: SLComposeSheetConfigurationItem!
override func viewDidLoad() {
extensionContainers = ExtensionContainersFile.read()
flattenedContainers = extensionContainers?.flattened ?? [ExtensionContainer]()
if let extensionContainers = extensionContainers {
@@ -92,15 +92,15 @@ final class ShareViewController: SLComposeServiceViewController, ShareFolderPick
return
})
}
// Reddit in particular doesn't pass the URL correctly and instead puts it in the contentText
url = URL(string: contentText)
}
override func isContentValid() -> Bool {
return url != nil && selectedContainer != nil
}
override func didSelectPost() {
guard let url = url, let selectedContainer = selectedContainer, let containerID = selectedContainer.containerID else {
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
@@ -111,13 +111,13 @@ final class ShareViewController: SLComposeServiceViewController, ShareFolderPick
if !contentText.mayBeURL {
name = contentText.isEmpty ? nil : contentText
}
let request = ExtensionFeedAddRequest(name: name, feedURL: url, destinationContainerID: containerID)
ExtensionFeedAddRequestFile.save(request)
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
func shareFolderPickerDidSelect(_ container: ExtensionContainer) {
ShareDefaultContainer.saveDefaultContainer(container)
self.selectedContainer = container
@@ -126,37 +126,37 @@ final class ShareViewController: SLComposeServiceViewController, ShareFolderPick
}
override func configurationItems() -> [Any]! {
// To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
guard let urlItem = SLComposeSheetConfigurationItem() else { return nil }
urlItem.title = "URL"
urlItem.value = url?.absoluteString ?? ""
folderItem = SLComposeSheetConfigurationItem()
folderItem.title = "Folder"
updateFolderItemValue()
folderItem.tapHandler = {
let folderPickerController = ShareFolderPickerController()
folderPickerController.navigationController?.title = NSLocalizedString("Folder", comment: "Folder")
folderPickerController.delegate = self
folderPickerController.containers = self.flattenedContainers
folderPickerController.selectedContainerID = self.selectedContainer?.containerID
self.pushConfigurationViewController(folderPickerController)
}
return [folderItem!, urlItem]
}
}
private extension ShareViewController {
func updateFolderItemValue() {
if let account = selectedContainer as? ExtensionAccount {
self.folderItem.value = account.name
@@ -164,5 +164,5 @@ private extension ShareViewController {
self.folderItem.value = "\(folder.accountName) / \(folder.name)"
}
}
}
+1 -1
View File
@@ -35,5 +35,5 @@ final class TitleActivityItemSource: NSObject, UIActivityItemSource {
return NSNull()
}
}
}
+4 -4
View File
@@ -10,16 +10,16 @@ import Foundation
/// Used to select which animations should be performed
public struct Animations: OptionSet {
/// Selections and deselections will be animated.
public static let select = Animations(rawValue: 1)
/// Scrolling will be animated
public static let scroll = Animations(rawValue: 2)
/// Pushing and popping navigation view controllers will be animated
public static let navigation = Animations(rawValue: 4)
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
+3 -3
View File
@@ -9,12 +9,12 @@
import UIKit
extension Array where Element == CGRect {
func maxY() -> CGFloat {
var y: CGFloat = 0.0
self.forEach { y = Swift.max(y, $0.maxY) }
return y
}
}
+4 -4
View File
@@ -9,17 +9,17 @@
import Foundation
extension Bundle {
var appName: String {
return infoDictionary?["CFBundleName"] as! String
}
var versionNumber: String {
return infoDictionary?["CFBundleShortVersionString"] as! String
}
var buildNumber: String {
return infoDictionary?["CFBundleVersion"] as! String
}
}
@@ -9,11 +9,11 @@
import UIKit
final class CroppingPreviewParameters: UIPreviewParameters {
override init() {
super.init()
}
init(view: UIView) {
super.init()
let newBounds = CGRect(x: 1, y: 1, width: view.bounds.width - 2, height: view.bounds.height - 2)
+4 -4
View File
@@ -11,19 +11,19 @@ import UIKit
final class ImageHeaderView: UITableViewHeaderFooterView {
static let rowHeight = CGFloat(integerLiteral: 88)
var imageView = UIImageView()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
imageView.tintColor = UIColor.label
imageView.contentMode = .scaleAspectFit
@@ -12,10 +12,10 @@ final class ModalNavigationController: UINavigationController {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// This hack is to resolve https://github.com/brentsimmons/NetNewsWire/issues/1301
let frame = navigationBar.frame
navigationBar.frame = CGRect(x: frame.minX, y: frame.minY, width: frame.size.width, height: 64.0)
}
}
+1 -1
View File
@@ -14,5 +14,5 @@ final class NonIntrinsicLabel: UILabel {
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
}
@@ -10,7 +10,7 @@
import UIKit
final class PoppableGestureRecognizerDelegate: NSObject, UIGestureRecognizerDelegate {
weak var navigationController: UINavigationController?
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
@@ -20,12 +20,12 @@ final class PoppableGestureRecognizerDelegate: NSObject, UIGestureRecognizerDele
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if otherGestureRecognizer is UIPanGestureRecognizer {
return true
}
return false
}
}
+3 -3
View File
@@ -9,17 +9,17 @@
import UIKit
extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.height)
}
func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.width)
}
}
+13 -13
View File
@@ -13,7 +13,7 @@ final class TickMarkSlider: UISlider {
private var enableFeedback = false
private let feedbackGenerator = UISelectionFeedbackGenerator()
private var roundedValue: Float?
override var value: Float {
didSet {
@@ -24,17 +24,17 @@ final class TickMarkSlider: UISlider {
}
}
}
func addTickMarks() {
enableFeedback = true
let numberOfGaps = Int(maximumValue) - Int(minimumValue)
var gapLayoutGuides = [UILayoutGuide]()
for i in 0...numberOfGaps {
let tick = UIView()
tick.translatesAutoresizingMaskIntoConstraints = false
tick.backgroundColor = AppAssets.tickMarkColor
@@ -47,11 +47,11 @@ final class TickMarkSlider: UISlider {
if i == 0 {
tick.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
}
if let lastGapLayoutGuild = gapLayoutGuides.last {
lastGapLayoutGuild.trailingAnchor.constraint(equalTo: tick.leadingAnchor).isActive = true
}
if i != numberOfGaps {
let gapLayoutGuild = UILayoutGuide()
gapLayoutGuides.append(gapLayoutGuild)
@@ -60,17 +60,17 @@ final class TickMarkSlider: UISlider {
} else {
tick.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
}
}
if let firstGapLayoutGuild = gapLayoutGuides.first {
for i in 1..<gapLayoutGuides.count {
gapLayoutGuides[i].widthAnchor.constraint(equalTo: firstGapLayoutGuild.widthAnchor).isActive = true
}
}
}
override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let result = super.continueTracking(touch, with: event)
value = value.rounded()
@@ -80,5 +80,5 @@ final class TickMarkSlider: UISlider {
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
value = value.rounded()
}
}
@@ -12,7 +12,7 @@ extension UIActivityViewController {
convenience init(url: URL, title: String?, applicationActivities: [UIActivity]?) {
let itemSource = ArticleActivityItemSource(url: url, subject: title)
let titleSource = TitleActivityItemSource(title: title)
self.init(activityItems: [titleSource, itemSource], applicationActivities: applicationActivities)
}
}
@@ -9,7 +9,7 @@
import UIKit
public extension UIBarButtonItem {
@IBInspectable var accEnabled: Bool {
get {
return isAccessibilityElement
@@ -18,7 +18,7 @@ public extension UIBarButtonItem {
isAccessibilityElement = newValue
}
}
@IBInspectable var accLabelText: String? {
get {
return accessibilityLabel
@@ -27,5 +27,5 @@ public extension UIBarButtonItem {
accessibilityLabel = newValue
}
}
}
@@ -20,7 +20,7 @@ extension UICollectionView {
indexPath.row < dataSource.collectionView(self, numberOfItemsInSection: indexPath.section) else {
return
}
selectItem(at: indexPath, animated: animations.contains(.select), scrollPosition: [])
if !indexPathsForVisibleItems.contains(indexPath) {
+4 -4
View File
@@ -9,7 +9,7 @@
import UIKit
extension UIFont {
func withTraits(traits:UIFontDescriptor.SymbolicTraits) -> UIFont {
if let descriptor = fontDescriptor.withSymbolicTraits(traits) {
return UIFont(descriptor: descriptor, size: 0) //size 0 means keep the size as it is
@@ -17,13 +17,13 @@ extension UIFont {
return self
}
}
func bold() -> UIFont {
return withTraits(traits: .traitBold)
}
func italic() -> UIFont {
return withTraits(traits: .traitItalic)
}
}
@@ -9,7 +9,7 @@
import UIKit
extension UIPageViewController {
var scrollViewInsidePageControl: UIScrollView? {
for view in view.subviews {
if let scrollView = view as? UIScrollView {
@@ -18,5 +18,5 @@ extension UIPageViewController {
}
return nil
}
}
@@ -9,39 +9,39 @@
import UIKit
extension UIStoryboard {
static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 400.0)
static var main: UIStoryboard {
return UIStoryboard(name: "Main", bundle: nil)
}
static var add: UIStoryboard {
return UIStoryboard(name: "Add", bundle: nil)
}
static var settings: UIStoryboard {
return UIStoryboard(name: "Settings", bundle: nil)
}
static var inspector: UIStoryboard {
return UIStoryboard(name: "Inspector", bundle: nil)
}
static var account: UIStoryboard {
return UIStoryboard(name: "Account", bundle: nil)
}
func instantiateController<T>(ofType type: T.Type = T.self) -> T where T: UIViewController {
let storyboardId = String(describing: type)
guard let viewController = instantiateViewController(withIdentifier: storyboardId) as? T else {
print("Unable to load view with Scene Identifier: \(storyboardId)")
fatalError()
}
return viewController
}
}
@@ -9,7 +9,7 @@
import UIKit
extension UITableView {
/**
Selects a row and scrolls it to the middle if it is not visible
*/
@@ -20,7 +20,7 @@ extension UITableView {
indexPath.row < dataSource.tableView(self, numberOfRowsInSection: indexPath.section) else {
return
}
selectRow(at: indexPath, animated: animations.contains(.select), scrollPosition: .none)
if let visibleIndexPaths = indexPathsForRows(in: safeAreaLayoutGuide.layoutFrame) {
@@ -29,12 +29,12 @@ extension UITableView {
}
}
}
func cellCompletelyVisible(_ indexPath: IndexPath) -> Bool {
let rect = rectForRow(at: indexPath)
return safeAreaLayoutGuide.layoutFrame.contains(rect)
}
public func middleVisibleRow() -> IndexPath? {
if let visibleIndexPaths = indexPathsForRows(in: safeAreaLayoutGuide.layoutFrame), visibleIndexPaths.count > 2 {
return visibleIndexPaths[visibleIndexPaths.count / 2]
@@ -11,7 +11,7 @@ import RSCore
import Account
extension UIViewController {
func presentError(_ error: Error, dismiss: (() -> Void)? = nil) {
if let accountError = error as? AccountError, accountError.isCredentialsError {
presentAccountError(accountError, dismiss: dismiss)
@@ -41,7 +41,7 @@ extension UIViewController {
let localizedError = NSLocalizedString("This theme cannot be used because of data corruption in the Info.plist. %@.", comment: "Decoding key missing")
informativeText = NSString.localizedStringWithFormat(localizedError as NSString, debugDescription) as String
presentError(title: errorTitle, message: informativeText, dismiss: dismiss)
default:
informativeText = error.localizedDescription
presentError(title: errorTitle, message: informativeText, dismiss: dismiss)
@@ -61,44 +61,44 @@ extension UIViewController {
}
private extension UIViewController {
func presentAccountError(_ error: AccountError, dismiss: (() -> Void)? = nil) {
let title = NSLocalizedString("Account Error", comment: "Account Error")
let alertController = UIAlertController(title: title, message: error.localizedDescription, preferredStyle: .alert)
if error.account?.type == .feedbin {
let credentialsTitle = NSLocalizedString("Update Credentials", comment: "Update Credentials")
let credentialsAction = UIAlertAction(title: credentialsTitle, style: .default) { [weak self] _ in
dismiss?()
let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "FeedbinAccountNavigationViewController") as! UINavigationController
navController.modalPresentationStyle = .formSheet
let addViewController = navController.topViewController as! FeedbinAccountViewController
addViewController.account = error.account
self?.present(navController, animated: true)
}
alertController.addAction(credentialsAction)
alertController.preferredAction = credentialsAction
}
let dismissTitle = NSLocalizedString("OK", comment: "OK")
let dismissAction = UIAlertAction(title: dismissTitle, style: .default) { _ in
dismiss?()
}
alertController.addAction(dismissAction)
self.present(alertController, animated: true, completion: nil)
}
func presentErrorWithRecovery(error: RecoverableError & LocalizedError, dismiss: (() -> Void)? = nil) {
let title = error.errorDescription ?? NSLocalizedString("Error", comment: "Error")
let message = [error.failureReason, error.recoverySuggestion].compactMap { $0 }.joined(separator: " ")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
// Add recovery options as buttons
for (index, option) in error.recoveryOptions.enumerated() {
let action = UIAlertAction(title: option, style: index == 0 ? .default : .cancel) { _ in
@@ -106,13 +106,13 @@ private extension UIViewController {
_ = error.attemptRecovery(optionIndex: index)
}
alertController.addAction(action)
// Make the first option the preferred action
if index == 0 {
alertController.preferredAction = action
}
}
self.present(alertController, animated: true, completion: nil)
}
+3 -3
View File
@@ -9,7 +9,7 @@
import UIKit
final class VibrantButton: UIButton {
@IBInspectable var backgroundHighlightColor: UIColor = AppAssets.secondaryAccentColor
override init(frame: CGRect) {
@@ -20,7 +20,7 @@ final class VibrantButton: UIButton {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
setTitleColor(AppAssets.vibrantTextColor, for: .highlighted)
let disabledColor = AppAssets.secondaryAccentColor.withAlphaComponent(0.5)
@@ -47,5 +47,5 @@ final class VibrantButton: UIButton {
isHighlighted = false
super.touchesCancelled(touches, with: event)
}
}
+3 -3
View File
@@ -9,17 +9,17 @@
import UIKit
final class VibrantLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
highlightedTextColor = AppAssets.vibrantTextColor
}
+16 -16
View File
@@ -9,27 +9,27 @@
import UIKit
class VibrantTableViewCell: UITableViewCell {
static let duration: TimeInterval = 0.6
var labelColor: UIColor {
return isHighlighted || isSelected ? AppAssets.vibrantTextColor : UIColor.label
}
var secondaryLabelColor: UIColor {
return isHighlighted || isSelected ? AppAssets.vibrantTextColor : UIColor.secondaryLabel
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
applyThemeProperties()
}
@@ -43,7 +43,7 @@ class VibrantTableViewCell: UITableViewCell {
super.setSelected(selected, animated: animated)
updateVibrancy(animated: animated)
}
/// Subclass overrides should call super
func applyThemeProperties() {
let selectedBackgroundView = UIView(frame: .zero)
@@ -56,7 +56,7 @@ class VibrantTableViewCell: UITableViewCell {
updateLabelVibrancy(textLabel, color: labelColor, animated: animated)
updateLabelVibrancy(detailTextLabel, color: labelColor, animated: animated)
}
func updateLabelVibrancy(_ label: UILabel?, color: UIColor, animated: Bool) {
guard let label = label else { return }
if animated {
@@ -67,33 +67,33 @@ class VibrantTableViewCell: UITableViewCell {
label.textColor = color
}
}
}
class VibrantBasicTableViewCell: VibrantTableViewCell {
@IBOutlet private var label: UILabel!
@IBOutlet private var detail: UILabel!
@IBOutlet private var icon: UIImageView!
@IBInspectable var imageNormal: UIImage?
@IBInspectable var imageSelected: UIImage?
var iconTint: UIColor {
return isHighlighted || isSelected ? labelColor : AppAssets.primaryAccentColor
}
var iconImage: UIImage? {
return isHighlighted || isSelected ? imageSelected : imageNormal
}
override func updateVibrancy(animated: Bool) {
super.updateVibrancy(animated: animated)
updateIconVibrancy(icon, color: iconTint, image: iconImage, animated: animated)
updateLabelVibrancy(label, color: labelColor, animated: animated)
updateLabelVibrancy(detail, color: secondaryLabelColor, animated: animated)
}
private func updateIconVibrancy(_ icon: UIImageView?, color: UIColor, image: UIImage?, animated: Bool) {
guard let icon = icon else { return }
if animated {
@@ -106,5 +106,5 @@ class VibrantBasicTableViewCell: VibrantTableViewCell {
icon.image = image
}
}
}