Compare commits

..

9 Commits

11 changed files with 946 additions and 90 deletions

View File

@ -417,32 +417,46 @@ public class Client {
} }
// MARK: - Instance // MARK: - Instance
public static func getTrendingHashtags(limit: Int? = nil) -> Request<[Hashtag]> { public static func getTrendingHashtagsDeprecated(limit: Int? = nil, offset: Int? = nil) -> Request<[Hashtag]> {
let parameters: [Parameter] var parameters: [Parameter] = []
if let limit = limit { if let limit {
parameters = ["limit" => limit] parameters.append("limit" => limit)
} else { }
parameters = [] if let offset {
parameters.append("offset" => offset)
} }
return Request<[Hashtag]>(method: .get, path: "/api/v1/trends", queryParameters: parameters) return Request<[Hashtag]>(method: .get, path: "/api/v1/trends", queryParameters: parameters)
} }
public static func getTrendingStatuses(limit: Int? = nil) -> Request<[Status]> { public static func getTrendingHashtags(limit: Int? = nil, offset: Int? = nil) -> Request<[Hashtag]> {
let parameters: [Parameter] var parameters: [Parameter] = []
if let limit = limit { if let limit {
parameters = ["limit" => limit] parameters.append("limit" => limit)
} else { }
parameters = [] if let offset {
parameters.append("offset" => offset)
}
return Request<[Hashtag]>(method: .get, path: "/api/v1/trends/tags", queryParameters: parameters)
}
public static func getTrendingStatuses(limit: Int? = nil, offset: Int? = nil) -> Request<[Status]> {
var parameters: [Parameter] = []
if let limit {
parameters.append("limit" => limit)
}
if let offset {
parameters.append("offset" => offset)
} }
return Request(method: .get, path: "/api/v1/trends/statuses", queryParameters: parameters) return Request(method: .get, path: "/api/v1/trends/statuses", queryParameters: parameters)
} }
public static func getTrendingLinks(limit: Int? = nil) -> Request<[Card]> { public static func getTrendingLinks(limit: Int? = nil, offset: Int? = nil) -> Request<[Card]> {
let parameters: [Parameter] var parameters: [Parameter] = []
if let limit = limit { if let limit {
parameters = ["limit" => limit] parameters.append("limit" => limit)
} else { }
parameters = [] if let offset {
parameters.append("offset" => offset)
} }
return Request(method: .get, path: "/api/v1/trends/links", queryParameters: parameters) return Request(method: .get, path: "/api/v1/trends/links", queryParameters: parameters)
} }

View File

@ -200,6 +200,7 @@
D681E4D7246E32290053414F /* StatusActivityItemSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = D681E4D6246E32290053414F /* StatusActivityItemSource.swift */; }; D681E4D7246E32290053414F /* StatusActivityItemSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = D681E4D6246E32290053414F /* StatusActivityItemSource.swift */; };
D681E4D9246E346E0053414F /* AccountActivityItemSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = D681E4D8246E346E0053414F /* AccountActivityItemSource.swift */; }; D681E4D9246E346E0053414F /* AccountActivityItemSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = D681E4D8246E346E0053414F /* AccountActivityItemSource.swift */; };
D68232F72464F4FD00325FB8 /* ComposeDrawingViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D68232F62464F4FD00325FB8 /* ComposeDrawingViewController.swift */; }; D68232F72464F4FD00325FB8 /* ComposeDrawingViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D68232F62464F4FD00325FB8 /* ComposeDrawingViewController.swift */; };
D68329EF299540050026EB24 /* MoreTrendsFooterCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = D68329EE299540050026EB24 /* MoreTrendsFooterCollectionViewCell.swift */; };
D686BBE324FBF8110068E6AA /* WrappedProgressView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D686BBE224FBF8110068E6AA /* WrappedProgressView.swift */; }; D686BBE324FBF8110068E6AA /* WrappedProgressView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D686BBE224FBF8110068E6AA /* WrappedProgressView.swift */; };
D6895DC228D65274006341DA /* CustomAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6895DC128D65274006341DA /* CustomAlertController.swift */; }; D6895DC228D65274006341DA /* CustomAlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6895DC128D65274006341DA /* CustomAlertController.swift */; };
D6895DC428D65342006341DA /* ConfirmReblogStatusPreviewView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6895DC328D65342006341DA /* ConfirmReblogStatusPreviewView.swift */; }; D6895DC428D65342006341DA /* ConfirmReblogStatusPreviewView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6895DC328D65342006341DA /* ConfirmReblogStatusPreviewView.swift */; };
@ -334,6 +335,7 @@
D6DD353F22F502EC00A9563A /* Preferences+Notification.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DD353E22F502EC00A9563A /* Preferences+Notification.swift */; }; D6DD353F22F502EC00A9563A /* Preferences+Notification.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DD353E22F502EC00A9563A /* Preferences+Notification.swift */; };
D6DD8FFD298495A8002AD3FD /* LogoutService.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DD8FFC298495A8002AD3FD /* LogoutService.swift */; }; D6DD8FFD298495A8002AD3FD /* LogoutService.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DD8FFC298495A8002AD3FD /* LogoutService.swift */; };
D6DD8FFF2984D327002AD3FD /* BookmarksViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DD8FFE2984D327002AD3FD /* BookmarksViewController.swift */; }; D6DD8FFF2984D327002AD3FD /* BookmarksViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DD8FFE2984D327002AD3FD /* BookmarksViewController.swift */; };
D6DD996B2998611A0015C962 /* SuggestedProfilesViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DD996A2998611A0015C962 /* SuggestedProfilesViewController.swift */; };
D6DF95C12533F5DE0027A9B6 /* RelationshipMO.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DF95C02533F5DE0027A9B6 /* RelationshipMO.swift */; }; D6DF95C12533F5DE0027A9B6 /* RelationshipMO.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DF95C02533F5DE0027A9B6 /* RelationshipMO.swift */; };
D6DFC69E242C490400ACC392 /* TrackpadScrollGestureRecognizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DFC69D242C490400ACC392 /* TrackpadScrollGestureRecognizer.swift */; }; D6DFC69E242C490400ACC392 /* TrackpadScrollGestureRecognizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DFC69D242C490400ACC392 /* TrackpadScrollGestureRecognizer.swift */; };
D6DFC6A0242C4CCC00ACC392 /* Weak.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DFC69F242C4CCC00ACC392 /* Weak.swift */; }; D6DFC6A0242C4CCC00ACC392 /* Weak.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6DFC69F242C4CCC00ACC392 /* Weak.swift */; };
@ -612,6 +614,7 @@
D681E4D6246E32290053414F /* StatusActivityItemSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusActivityItemSource.swift; sourceTree = "<group>"; }; D681E4D6246E32290053414F /* StatusActivityItemSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusActivityItemSource.swift; sourceTree = "<group>"; };
D681E4D8246E346E0053414F /* AccountActivityItemSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountActivityItemSource.swift; sourceTree = "<group>"; }; D681E4D8246E346E0053414F /* AccountActivityItemSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountActivityItemSource.swift; sourceTree = "<group>"; };
D68232F62464F4FD00325FB8 /* ComposeDrawingViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposeDrawingViewController.swift; sourceTree = "<group>"; }; D68232F62464F4FD00325FB8 /* ComposeDrawingViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposeDrawingViewController.swift; sourceTree = "<group>"; };
D68329EE299540050026EB24 /* MoreTrendsFooterCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MoreTrendsFooterCollectionViewCell.swift; sourceTree = "<group>"; };
D686BBE224FBF8110068E6AA /* WrappedProgressView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WrappedProgressView.swift; sourceTree = "<group>"; }; D686BBE224FBF8110068E6AA /* WrappedProgressView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WrappedProgressView.swift; sourceTree = "<group>"; };
D6895DC128D65274006341DA /* CustomAlertController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomAlertController.swift; sourceTree = "<group>"; }; D6895DC128D65274006341DA /* CustomAlertController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomAlertController.swift; sourceTree = "<group>"; };
D6895DC328D65342006341DA /* ConfirmReblogStatusPreviewView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfirmReblogStatusPreviewView.swift; sourceTree = "<group>"; }; D6895DC328D65342006341DA /* ConfirmReblogStatusPreviewView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfirmReblogStatusPreviewView.swift; sourceTree = "<group>"; };
@ -754,6 +757,7 @@
D6DD353E22F502EC00A9563A /* Preferences+Notification.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Preferences+Notification.swift"; sourceTree = "<group>"; }; D6DD353E22F502EC00A9563A /* Preferences+Notification.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Preferences+Notification.swift"; sourceTree = "<group>"; };
D6DD8FFC298495A8002AD3FD /* LogoutService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogoutService.swift; sourceTree = "<group>"; }; D6DD8FFC298495A8002AD3FD /* LogoutService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogoutService.swift; sourceTree = "<group>"; };
D6DD8FFE2984D327002AD3FD /* BookmarksViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BookmarksViewController.swift; sourceTree = "<group>"; }; D6DD8FFE2984D327002AD3FD /* BookmarksViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BookmarksViewController.swift; sourceTree = "<group>"; };
D6DD996A2998611A0015C962 /* SuggestedProfilesViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SuggestedProfilesViewController.swift; sourceTree = "<group>"; };
D6DF95C02533F5DE0027A9B6 /* RelationshipMO.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RelationshipMO.swift; sourceTree = "<group>"; }; D6DF95C02533F5DE0027A9B6 /* RelationshipMO.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RelationshipMO.swift; sourceTree = "<group>"; };
D6DFC69D242C490400ACC392 /* TrackpadScrollGestureRecognizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackpadScrollGestureRecognizer.swift; sourceTree = "<group>"; }; D6DFC69D242C490400ACC392 /* TrackpadScrollGestureRecognizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrackpadScrollGestureRecognizer.swift; sourceTree = "<group>"; };
D6DFC69F242C4CCC00ACC392 /* Weak.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Weak.swift; sourceTree = "<group>"; }; D6DFC69F242C4CCC00ACC392 /* Weak.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Weak.swift; sourceTree = "<group>"; };
@ -945,6 +949,8 @@
D693A72D25CF91C6003A14E2 /* FeaturedProfileCollectionViewCell.swift */, D693A72D25CF91C6003A14E2 /* FeaturedProfileCollectionViewCell.swift */,
D693A72E25CF91C6003A14E2 /* FeaturedProfileCollectionViewCell.xib */, D693A72E25CF91C6003A14E2 /* FeaturedProfileCollectionViewCell.xib */,
D6C3F4FA299035650009FCFF /* TrendsViewController.swift */, D6C3F4FA299035650009FCFF /* TrendsViewController.swift */,
D68329EE299540050026EB24 /* MoreTrendsFooterCollectionViewCell.swift */,
D6DD996A2998611A0015C962 /* SuggestedProfilesViewController.swift */,
); );
path = Explore; path = Explore;
sourceTree = "<group>"; sourceTree = "<group>";
@ -1965,6 +1971,7 @@
D6093FB725BE0CF3004811E6 /* TrendHistoryView.swift in Sources */, D6093FB725BE0CF3004811E6 /* TrendHistoryView.swift in Sources */,
D6EBF01723C55E0D00AE061B /* UISceneSession+MastodonController.swift in Sources */, D6EBF01723C55E0D00AE061B /* UISceneSession+MastodonController.swift in Sources */,
D61F759229365C6C00C0B37F /* CollectionViewController.swift in Sources */, D61F759229365C6C00C0B37F /* CollectionViewController.swift in Sources */,
D6DD996B2998611A0015C962 /* SuggestedProfilesViewController.swift in Sources */,
D6DD8FFD298495A8002AD3FD /* LogoutService.swift in Sources */, D6DD8FFD298495A8002AD3FD /* LogoutService.swift in Sources */,
04DACE8C212CB14B009840C4 /* MainTabBarViewController.swift in Sources */, 04DACE8C212CB14B009840C4 /* MainTabBarViewController.swift in Sources */,
D68E525D24A3E8F00054355A /* InlineTrendsViewController.swift in Sources */, D68E525D24A3E8F00054355A /* InlineTrendsViewController.swift in Sources */,
@ -2072,6 +2079,7 @@
D6A00B1D26379FC900316AD4 /* PollOptionsView.swift in Sources */, D6A00B1D26379FC900316AD4 /* PollOptionsView.swift in Sources */,
D6DF95C12533F5DE0027A9B6 /* RelationshipMO.swift in Sources */, D6DF95C12533F5DE0027A9B6 /* RelationshipMO.swift in Sources */,
D6ADB6EE28EA74E8009924AB /* UIView+Configure.swift in Sources */, D6ADB6EE28EA74E8009924AB /* UIView+Configure.swift in Sources */,
D68329EF299540050026EB24 /* MoreTrendsFooterCollectionViewCell.swift in Sources */,
D623A5412635FB3C0095BD04 /* PollOptionView.swift in Sources */, D623A5412635FB3C0095BD04 /* PollOptionView.swift in Sources */,
D61F75B1293BD85300C0B37F /* CreateFilterService.swift in Sources */, D61F75B1293BD85300C0B37F /* CreateFilterService.swift in Sources */,
D65C6BF525478A9C00A6E89C /* BackgroundableViewController.swift in Sources */, D65C6BF525478A9C00A6E89C /* BackgroundableViewController.swift in Sources */,

View File

@ -0,0 +1,84 @@
//
// MoreTrendsFooterCollectionViewCell.swift
// Tusker
//
// Created by Shadowfacts on 2/9/23.
// Copyright © 2023 Shadowfacts. All rights reserved.
//
import UIKit
class MoreTrendsFooterCollectionViewCell: UICollectionViewCell {
weak var delegate: TuskerNavigationDelegate?
private var button = UIButton()
private var kind: Kind!
override init(frame: CGRect) {
super.init(frame: frame)
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(button)
NSLayoutConstraint.activate([
button.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
button.topAnchor.constraint(equalTo: contentView.topAnchor),
button.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateUI(_ kind: Kind) {
guard self.kind != kind else {
return
}
self.kind = kind
var config = UIButton.Configuration.plain()
var title: AttributedString
switch kind {
case .hashtags:
title = "More Trending Hashtags"
case .links:
title = "More Trending Links"
case .profileSuggestions:
title = "More Suggested Accounts"
}
title.font = .preferredFont(forTextStyle: .body).withTraits(.traitBold)!
config.attributedTitle = title
config.image = UIImage(systemName: "chevron.right")
config.imagePlacement = .trailing
config.buttonSize = .mini
button.configuration = config
}
@objc private func buttonPressed() {
guard let delegate else {
return
}
switch kind {
case nil:
return
case .hashtags:
delegate.show(TrendingHashtagsViewController(mastodonController: delegate.apiController))
case .links:
delegate.show(TrendingLinksViewController(mastodonController: delegate.apiController))
case .profileSuggestions:
delegate.show(SuggestedProfilesViewController(mastodonController: delegate.apiController))
}
}
}
extension MoreTrendsFooterCollectionViewCell {
enum Kind {
case hashtags
case links
case profileSuggestions
}
}

View File

@ -0,0 +1,212 @@
//
// SuggestedProfilesViewController.swift
// Tusker
//
// Created by Shadowfacts on 2/11/23.
// Copyright © 2023 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
class SuggestedProfilesViewController: UIViewController, CollectionViewController {
weak var mastodonController: MastodonController!
var collectionView: UICollectionView!
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var state = State.unloaded
init(mastodonController: MastodonController) {
self.mastodonController = mastodonController
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Suggested Accounts"
let layout = UICollectionViewCompositionalLayout { [unowned self] sectionIndex, environment in
switch dataSource.sectionIdentifier(for: sectionIndex) {
case nil:
fatalError()
case .loadingIndicator:
var config = UICollectionLayoutListConfiguration(appearance: .grouped)
config.backgroundColor = .appGroupedBackground
config.showsSeparators = false
return .list(using: config, layoutEnvironment: environment)
case .accounts:
let size = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(280))
let item = NSCollectionLayoutItem(layoutSize: size)
let item2 = NSCollectionLayoutItem(layoutSize: size)
let group = NSCollectionLayoutGroup.vertical(layoutSize: size, subitems: [item, item2])
group.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
group.interItemSpacing = .fixed(16)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 16
section.contentInsets = NSDirectionalEdgeInsets(top: 16, leading: 0, bottom: 16, trailing: 0)
return section
}
}
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.delegate = self
collectionView.dragDelegate = self
collectionView.backgroundColor = .appGroupedBackground
collectionView.allowsFocus = true
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
dataSource = createDataSource()
}
private func createDataSource() -> UICollectionViewDiffableDataSource<Section, Item> {
let loadingCell = UICollectionView.CellRegistration<LoadingCollectionViewCell, Void> { cell, indexPath, itemIdentifier in
cell.indicator.startAnimating()
}
let accountCell = UICollectionView.CellRegistration<SuggestedProfileCardCollectionViewCell, (String, Suggestion.Source)>(cellNib: UINib(nibName: "SuggestedProfileCardCollectionViewCell", bundle: .main)) { cell, indexPath, item in
cell.delegate = self
cell.updateUI(accountID: item.0, source: item.1)
}
return UICollectionViewDiffableDataSource(collectionView: collectionView) { collectionView, indexPath, itemIdentifier in
switch itemIdentifier {
case .loadingIndicator:
return collectionView.dequeueConfiguredReusableCell(using: loadingCell, for: indexPath, item: ())
case .account(let id, let source):
return collectionView.dequeueConfiguredReusableCell(using: accountCell, for: indexPath, item: (id, source))
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Task {
await loadInitial()
}
}
@MainActor
private func loadInitial() async {
guard case .unloaded = state else {
return
}
state = .loading
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.loadingIndicator])
snapshot.appendItems([.loadingIndicator])
await dataSource.apply(snapshot)
do {
let request = Client.getSuggestions(limit: 80)
let (suggestions, _) = try await mastodonController.run(request)
await mastodonController.persistentContainer.addAll(accounts: suggestions.map(\.account))
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.accounts])
snapshot.appendItems(suggestions.map { .account($0.account.id, $0.source) })
await dataSource.apply(snapshot)
state = .loaded
} catch {
state = .unloaded
let config = ToastConfiguration(from: error, with: "Error Loading Suggested Accounts", in: self) { [weak self] toast in
toast.dismissToast(animated: true)
await self?.loadInitial()
}
showToast(configuration: config, animated: true)
}
}
}
extension SuggestedProfilesViewController {
enum State {
case unloaded
case loading
case loaded
}
}
extension SuggestedProfilesViewController {
enum Section {
case loadingIndicator
case accounts
}
enum Item: Hashable {
case loadingIndicator
case account(String, Suggestion.Source)
}
}
extension SuggestedProfilesViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if case .account(_, _) = dataSource.itemIdentifier(for: indexPath) {
return true
} else {
return false
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard case .account(let id, _) = dataSource.itemIdentifier(for: indexPath) else {
return
}
selected(account: id)
}
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
guard case .account(let id, _) = dataSource.itemIdentifier(for: indexPath),
let cell = collectionView.cellForItem(at: indexPath) else {
return nil
}
return UIContextMenuConfiguration {
ProfileViewController(accountID: id, mastodonController: self.mastodonController)
} actionProvider: { _ in
UIMenu(children: self.actionsForProfile(accountID: id, source: .view(cell)))
}
}
func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
MenuPreviewHelper.willPerformPreviewAction(animator: animator, presenter: self)
}
}
extension SuggestedProfilesViewController: UICollectionViewDragDelegate {
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
guard case .account(let id, _) = dataSource.itemIdentifier(for: indexPath),
let account = mastodonController.persistentContainer.account(for: id) else {
return []
}
let provider = NSItemProvider(object: account.url as NSURL)
let activity = UserActivityManager.showProfileActivity(id: id, accountID: mastodonController.accountInfo!.id)
provider.registerObject(activity, visibility: .all)
return [UIDragItem(itemProvider: provider)]
}
}
extension SuggestedProfilesViewController: TuskerNavigationDelegate {
var apiController: MastodonController! { mastodonController }
}
extension SuggestedProfilesViewController: MenuActionProvider {
}
extension SuggestedProfilesViewController: ToastableViewController {
}

View File

@ -9,6 +9,7 @@
import UIKit import UIKit
import Pachyderm import Pachyderm
import WebURLFoundationExtras import WebURLFoundationExtras
import Combine
class TrendingHashtagsViewController: UIViewController { class TrendingHashtagsViewController: UIViewController {
@ -17,6 +18,9 @@ class TrendingHashtagsViewController: UIViewController {
private var collectionView: UICollectionView! private var collectionView: UICollectionView!
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>! private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var state = State.unloaded
private var confirmLoadMore = PassthroughSubject<Void, Never>()
init(mastodonController: MastodonController) { init(mastodonController: MastodonController) {
self.mastodonController = mastodonController self.mastodonController = mastodonController
@ -32,9 +36,21 @@ class TrendingHashtagsViewController: UIViewController {
title = NSLocalizedString("Trending Hashtags", comment: "trending hashtags screen title") title = NSLocalizedString("Trending Hashtags", comment: "trending hashtags screen title")
view.backgroundColor = .systemGroupedBackground view.backgroundColor = .appGroupedBackground
let config = UICollectionLayoutListConfiguration(appearance: .grouped) var config = UICollectionLayoutListConfiguration(appearance: .grouped)
config.backgroundColor = .appGroupedBackground
config.itemSeparatorHandler = { [unowned self] indexPath, sectionConfig in
guard let item = dataSource.itemIdentifier(for: indexPath) else {
return sectionConfig
}
var config = sectionConfig
if item.hideSeparators {
config.topSeparatorVisibility = .hidden
config.bottomSeparatorVisibility = .hidden
}
return config
}
let layout = UICollectionViewCompositionalLayout.list(using: config) let layout = UICollectionViewCompositionalLayout.list(using: config)
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
@ -43,14 +59,24 @@ class TrendingHashtagsViewController: UIViewController {
collectionView.allowsFocus = true collectionView.allowsFocus = true
view.addSubview(collectionView) view.addSubview(collectionView)
let registration = UICollectionView.CellRegistration<TrendingHashtagCollectionViewCell, Hashtag> { cell, indexPath, hashtag in let loadingCell = UICollectionView.CellRegistration<LoadingCollectionViewCell, Void> { cell, indexPath, itemIdentifier in
cell.indicator.startAnimating()
}
let hashtagCell = UICollectionView.CellRegistration<TrendingHashtagCollectionViewCell, Hashtag> { cell, indexPath, hashtag in
cell.updateUI(hashtag: hashtag) cell.updateUI(hashtag: hashtag)
} }
let confirmLoadMoreCell = UICollectionView.CellRegistration<ConfirmLoadMoreCollectionViewCell, Bool> { [unowned self] cell, indexPath, isLoading in
cell.confirmLoadMore = self.confirmLoadMore
cell.isLoading = isLoading
}
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { (collectionView, indexPath, item) in dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { (collectionView, indexPath, item) in
switch item { switch item {
case let .tag(hashtag): case .loadingIndicator:
return collectionView.dequeueConfiguredReusableCell(using: registration, for: indexPath, item: hashtag) return collectionView.dequeueConfiguredReusableCell(using: loadingCell, for: indexPath, item: ())
case .tag(let hashtag):
return collectionView.dequeueConfiguredReusableCell(using: hashtagCell, for: indexPath, item: hashtag)
case .confirmLoadMore(let loading):
return collectionView.dequeueConfiguredReusableCell(using: confirmLoadMoreCell, for: indexPath, item: loading)
} }
} }
} }
@ -58,18 +84,104 @@ class TrendingHashtagsViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) { override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated) super.viewWillAppear(animated)
let request = Client.getTrendingHashtags(limit: 10)
Task { Task {
guard let (hashtags, _) = try? await mastodonController.run(request) else { await loadInitial()
return
}
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.trendingTags])
snapshot.appendItems(hashtags.map { .tag($0) })
await dataSource.apply(snapshot)
} }
} }
private func request(offset: Int?) -> Request<[Hashtag]> {
if mastodonController.instanceFeatures.hasMastodonVersion(3, 5, 0) {
return Client.getTrendingHashtags(offset: offset)
} else {
return Client.getTrendingHashtagsDeprecated(offset: offset)
}
}
@MainActor
private func loadInitial() async {
guard case .unloaded = state else {
return
}
state = .loadingInitial
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.trendingTags])
snapshot.appendItems([.loadingIndicator])
await dataSource.apply(snapshot)
do {
let request = self.request(offset: nil)
let (hashtags, _) = try await mastodonController.run(request)
snapshot.deleteItems([.loadingIndicator])
snapshot.appendItems(hashtags.map { .tag($0) })
state = .loaded
await dataSource.apply(snapshot)
} catch {
snapshot.deleteItems([.loadingIndicator])
await dataSource.apply(snapshot)
state = .unloaded
let config = ToastConfiguration(from: error, with: "Error Loading Trending Tags", in: self) { [weak self] toast in
toast.dismissToast(animated: true)
await self?.loadInitial()
}
self.showToast(configuration: config, animated: true)
}
}
@MainActor
private func loadOlder() async {
guard case .loaded = state else {
return
}
state = .loadingOlder
let origSnapshot = dataSource.snapshot()
var snapshot = origSnapshot
if Preferences.shared.disableInfiniteScrolling {
snapshot.appendItems([.confirmLoadMore(false)])
await dataSource.apply(snapshot)
for await _ in confirmLoadMore.values {
break
}
snapshot.deleteItems([.confirmLoadMore(false)])
snapshot.appendItems([.confirmLoadMore(true)])
await dataSource.apply(snapshot, animatingDifferences: false)
} else {
snapshot.appendItems([.loadingIndicator])
await dataSource.apply(snapshot)
}
do {
let request = self.request(offset: snapshot.itemIdentifiers.count - 1)
let (hashtags, _) = try await mastodonController.run(request)
var snapshot = origSnapshot
snapshot.appendItems(hashtags.map { .tag($0) })
await dataSource.apply(snapshot)
} catch {
await dataSource.apply(origSnapshot)
let config = ToastConfiguration(from: error, with: "Error Loading More Tags", in: self) { [weak self] toast in
toast.dismissToast(animated: true)
await self?.loadOlder()
}
self.showToast(configuration: config, animated: true)
}
state = .loaded
}
}
extension TrendingHashtagsViewController {
enum State {
case unloaded
case loadingInitial
case loaded
case loadingOlder
}
} }
extension TrendingHashtagsViewController { extension TrendingHashtagsViewController {
@ -77,11 +189,45 @@ extension TrendingHashtagsViewController {
case trendingTags case trendingTags
} }
enum Item: Hashable { enum Item: Hashable {
case loadingIndicator
case tag(Hashtag) case tag(Hashtag)
case confirmLoadMore(Bool)
var hideSeparators: Bool {
switch self {
case .loadingIndicator:
return true
case .tag(_):
return false
case .confirmLoadMore(_):
return false
}
}
var shouldSelect: Bool {
if case .tag(_) = self {
return true
} else {
return false
}
}
} }
} }
extension TrendingHashtagsViewController: UICollectionViewDelegate { extension TrendingHashtagsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.section == collectionView.numberOfSections - 1,
indexPath.row == collectionView.numberOfItems(inSection: indexPath.section) - 1 {
Task {
await self.loadOlder()
}
}
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return dataSource.itemIdentifier(for: indexPath)?.shouldSelect ?? false
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath), guard let item = dataSource.itemIdentifier(for: indexPath),
case let .tag(hashtag) = item else { case let .tag(hashtag) = item else {

View File

@ -21,6 +21,29 @@ class TrendingLinkCardCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var providerLabel: UILabel! @IBOutlet weak var providerLabel: UILabel!
@IBOutlet weak var activityLabel: UILabel! @IBOutlet weak var activityLabel: UILabel!
@IBOutlet weak var historyView: TrendHistoryView! @IBOutlet weak var historyView: TrendHistoryView!
private var thumbnailAspectRatioConstraint: NSLayoutConstraint?
var verticalSize: VerticalSize! {
didSet {
guard oldValue != verticalSize else {
return
}
switch verticalSize {
case nil:
fatalError()
case .regular:
thumbnailAspectRatioConstraint?.isActive = false
thumbnailAspectRatioConstraint = thumbnailView.widthAnchor.constraint(equalTo: thumbnailView.heightAnchor, multiplier: 4/3)
thumbnailAspectRatioConstraint!.isActive = true
descriptionLabel.numberOfLines = 3
case .compact:
thumbnailAspectRatioConstraint?.isActive = false
thumbnailAspectRatioConstraint = thumbnailView.widthAnchor.constraint(equalTo: thumbnailView.heightAnchor, multiplier: 2/1)
thumbnailAspectRatioConstraint!.isActive = true
descriptionLabel.numberOfLines = 5
}
}
}
private var hoverGestureAnimator: UIViewPropertyAnimator? private var hoverGestureAnimator: UIViewPropertyAnimator?
@ -37,6 +60,8 @@ class TrendingLinkCardCollectionViewCell: UICollectionViewCell {
contentView.backgroundColor = .appGroupedCellBackground contentView.backgroundColor = .appGroupedCellBackground
updateLayerColors() updateLayerColors()
verticalSize = .regular
addGestureRecognizer(UIHoverGestureRecognizer(target: self, action: #selector(hoverRecognized))) addGestureRecognizer(UIHoverGestureRecognizer(target: self, action: #selector(hoverRecognized)))
} }
@ -137,3 +162,9 @@ class TrendingLinkCardCollectionViewCell: UICollectionViewCell {
} }
} }
extension TrendingLinkCardCollectionViewCell {
enum VerticalSize {
case regular, compact
}
}

View File

@ -21,7 +21,7 @@
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="h3b-Mf-lD6" customClass="CachedImageView" customModule="Tusker" customModuleProvider="target"> <imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="h3b-Mf-lD6" customClass="CachedImageView" customModule="Tusker" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="300" height="225"/> <rect key="frame" x="0.0" y="0.0" width="300" height="225"/>
<constraints> <constraints>
<constraint firstAttribute="width" secondItem="h3b-Mf-lD6" secondAttribute="height" multiplier="4:3" id="QDY-8a-LYC"/> <constraint firstAttribute="width" secondItem="h3b-Mf-lD6" secondAttribute="height" multiplier="4:3" placeholder="YES" id="QDY-8a-LYC"/>
</constraints> </constraints>
</imageView> </imageView>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" alignment="top" spacing="4" translatesAutoresizingMaskIntoConstraints="NO" id="LpU-m4-guC"> <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" alignment="top" spacing="4" translatesAutoresizingMaskIntoConstraints="NO" id="LpU-m4-guC">
@ -56,9 +56,9 @@
</constraints> </constraints>
</view> </view>
<visualEffectView opaque="NO" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="cWo-9n-z42"> <visualEffectView opaque="NO" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="cWo-9n-z42">
<rect key="frame" x="0.0" y="196.33333333333334" width="300" height="28.666666666666657"/> <rect key="frame" x="0.0" y="196.66666666666666" width="300" height="28.333333333333343"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO" id="ktv-3s-cp9"> <view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO" id="ktv-3s-cp9">
<rect key="frame" x="0.0" y="0.0" width="300" height="28.666666666666657"/> <rect key="frame" x="0.0" y="0.0" width="300" height="28.333333333333343"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews> <subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="2" baselineAdjustment="alignBaselines" adjustsLetterSpacingToFitWidth="YES" showsExpansionTextWhenTruncated="YES" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Ho3-cU-IGi"> <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="2" baselineAdjustment="alignBaselines" adjustsLetterSpacingToFitWidth="YES" showsExpansionTextWhenTruncated="YES" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Ho3-cU-IGi">

View File

@ -10,19 +10,22 @@ import UIKit
import Pachyderm import Pachyderm
import WebURLFoundationExtras import WebURLFoundationExtras
import SafariServices import SafariServices
import Combine
class TrendingLinksViewController: EnhancedTableViewController { class TrendingLinksViewController: UIViewController, CollectionViewController {
weak var mastodonController: MastodonController! weak var mastodonController: MastodonController!
private var dataSource: UITableViewDiffableDataSource<Section, Item>! var collectionView: UICollectionView!
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var state = State.unloaded
private let confirmLoadMore = PassthroughSubject<Void, Never>()
init(mastodonController: MastodonController) { init(mastodonController: MastodonController) {
self.mastodonController = mastodonController self.mastodonController = mastodonController
super.init(style: .grouped) super.init(nibName: nil, bundle: nil)
dragEnabled = true
} }
required init?(coder: NSCoder) { required init?(coder: NSCoder) {
@ -34,73 +37,259 @@ class TrendingLinksViewController: EnhancedTableViewController {
title = NSLocalizedString("Trending Links", comment: "trending links screen title") title = NSLocalizedString("Trending Links", comment: "trending links screen title")
tableView.register(TrendingLinkTableViewCell.self, forCellReuseIdentifier: "trendingLinkCell") let layout = UICollectionViewCompositionalLayout { [unowned self] sectionIndex, environment in
tableView.estimatedRowHeight = 100 switch dataSource.sectionIdentifier(for: sectionIndex) {
tableView.allowsFocus = true case nil:
tableView.backgroundColor = .appGroupedBackground fatalError()
case .loadingIndicator:
var config = UICollectionLayoutListConfiguration(appearance: .grouped)
config.backgroundColor = .appGroupedBackground
config.showsSeparators = false
return .list(using: config, layoutEnvironment: environment)
case .links:
let size = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(280))
let item = NSCollectionLayoutItem(layoutSize: size)
let item2 = NSCollectionLayoutItem(layoutSize: size)
let group = NSCollectionLayoutGroup.vertical(layoutSize: size, subitems: [item, item2])
group.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
group.interItemSpacing = .fixed(16)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 16
section.contentInsets = NSDirectionalEdgeInsets(top: 16, leading: 0, bottom: 16, trailing: 0)
return section
}
}
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.delegate = self
collectionView.dragDelegate = self
collectionView.backgroundColor = .appGroupedBackground
collectionView.allowsFocus = true
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
dataSource = UITableViewDiffableDataSource(tableView: tableView, cellProvider: { tableView, indexPath, item in dataSource = createDataSource()
let cell = tableView.dequeueReusableCell(withIdentifier: "trendingLinkCell", for: indexPath) as! TrendingLinkTableViewCell }
cell.updateUI(card: item.card)
return cell private func createDataSource() -> UICollectionViewDiffableDataSource<Section, Item> {
}) let loadingCell = UICollectionView.CellRegistration<LoadingCollectionViewCell, Void> { cell, indexPath, itemIdentifier in
cell.indicator.startAnimating()
}
let linkCell = UICollectionView.CellRegistration<TrendingLinkCardCollectionViewCell, Card>(cellNib: UINib(nibName: "TrendingLinkCardCollectionViewCell", bundle: .main)) { cell, indexPath, item in
cell.verticalSize = .compact
cell.updateUI(card: item)
}
let confirmLoadMoreCell = UICollectionView.CellRegistration<ConfirmLoadMoreCollectionViewCell, Bool> { cell, indexPath, isLoading in
cell.confirmLoadMore = self.confirmLoadMore
cell.isLoading = isLoading
}
return UICollectionViewDiffableDataSource(collectionView: collectionView) { collectionView, indexPath, itemIdentifier in
switch itemIdentifier {
case .loadingIndicator:
return collectionView.dequeueConfiguredReusableCell(using: loadingCell, for: indexPath, item: ())
case .link(let card):
return collectionView.dequeueConfiguredReusableCell(using: linkCell, for: indexPath, item: card)
case .confirmLoadMore(let loading):
return collectionView.dequeueConfiguredReusableCell(using: confirmLoadMoreCell, for: indexPath, item: loading)
}
}
} }
override func viewWillAppear(_ animated: Bool) { override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated) super.viewWillAppear(animated)
let request = Client.getTrendingLinks()
Task { Task {
guard let (links, _) = try? await mastodonController.run(request) else { await loadInitial()
return
}
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.links])
snapshot.appendItems(links.map(Item.init))
await dataSource.apply(snapshot)
} }
} }
// MARK: - Table View Delegate @MainActor
private func loadInitial() async {
guard case .unloaded = state else {
return
}
state = .loading
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.loadingIndicator])
snapshot.appendItems([.loadingIndicator])
await dataSource.apply(snapshot)
do {
let request = Client.getTrendingLinks()
let (links, _) = try await mastodonController.run(request)
snapshot.deleteSections([.loadingIndicator])
snapshot.appendSections([.links])
snapshot.appendItems(links.map { .link($0) })
state = .loaded
await dataSource.apply(snapshot)
} catch {
await dataSource.apply(NSDiffableDataSourceSnapshot())
state = .unloaded
let config = ToastConfiguration(from: error, with: "Error Loading Trending Links", in: self) { [weak self] toast in
toast.dismissToast(animated: true)
await self?.loadInitial()
}
self.showToast(configuration: config, animated: true)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { @MainActor
guard let item = dataSource.itemIdentifier(for: indexPath), private func loadOlder() async {
let url = URL(item.card.url) else { guard case .loaded = state else {
return
}
state = .loadingOlder
let origSnapshot = dataSource.snapshot()
var snapshot = origSnapshot
if Preferences.shared.disableInfiniteScrolling {
snapshot.appendSections([.loadingIndicator])
snapshot.appendItems([.confirmLoadMore(false)], toSection: .loadingIndicator)
await dataSource.apply(snapshot)
for await _ in confirmLoadMore.values {
break
}
snapshot.deleteItems([.confirmLoadMore(false)])
snapshot.appendItems([.confirmLoadMore(true)], toSection: .loadingIndicator)
await dataSource.apply(snapshot, animatingDifferences: false)
} else {
snapshot.appendSections([.loadingIndicator])
snapshot.appendItems([.loadingIndicator], toSection: .loadingIndicator)
await dataSource.apply(snapshot)
}
do {
let request = Client.getTrendingLinks(offset: origSnapshot.itemIdentifiers.count)
let (links, _) = try await mastodonController.run(request)
var snapshot = origSnapshot
snapshot.appendItems(links.map { .link($0) }, toSection: .links)
await dataSource.apply(snapshot)
} catch {
await dataSource.apply(origSnapshot)
let config = ToastConfiguration(from: error, with: "Erorr Loading More Links", in: self) { [weak self] toast in
toast.dismissToast(animated: true)
await self?.loadOlder()
}
self.showToast(configuration: config, animated: true)
}
}
}
extension TrendingLinksViewController {
enum State {
case unloaded
case loading
case loaded
case loadingOlder
}
}
extension TrendingLinksViewController {
enum Section {
case loadingIndicator
case links
}
enum Item: Hashable {
case loadingIndicator
case link(Card)
case confirmLoadMore(Bool)
static func ==(lhs: Item, rhs: Item) -> Bool {
switch (lhs, rhs) {
case (.loadingIndicator, .loadingIndicator):
return true
case (.link(let a), .link(let b)):
return a.url == b.url
case (.confirmLoadMore(let a), .confirmLoadMore(let b)):
return a == b
default:
return false
}
}
func hash(into hasher: inout Hasher) {
switch self {
case .loadingIndicator:
hasher.combine(0)
case .link(let card):
hasher.combine(1)
hasher.combine(card.url)
case .confirmLoadMore(let loading):
hasher.combine(2)
hasher.combine(loading)
}
}
var shouldSelect: Bool {
if case .link(_) = self {
return true
} else {
return false
}
}
}
}
extension TrendingLinksViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.section == collectionView.numberOfSections - 1,
indexPath.row == collectionView.numberOfItems(inSection: indexPath.section) - 1 {
Task {
await loadOlder()
}
}
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return dataSource.itemIdentifier(for: indexPath)?.shouldSelect ?? false
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard case .link(let card) = dataSource.itemIdentifier(for: indexPath),
let url = URL(card.url) else {
return return
} }
selected(url: url) selected(url: url)
} }
override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
guard let item = dataSource.itemIdentifier(for: indexPath), guard case .link(let card) = dataSource.itemIdentifier(for: indexPath),
let url = URL(item.card.url) else { let url = URL(card.url),
let cell = collectionView.cellForItem(at: indexPath) else {
return nil return nil
} }
return UIContextMenuConfiguration(identifier: nil) { return UIContextMenuConfiguration {
let vc = SFSafariViewController(url: url) let vc = SFSafariViewController(url: url)
vc.preferredControlTintColor = Preferences.shared.accentColor.color vc.preferredControlTintColor = Preferences.shared.accentColor.color
return vc return vc
} actionProvider: { _ in } actionProvider: { _ in
return UIMenu(children: self.actionsForTrendingLink(card: item.card)) UIMenu(children: self.actionsForTrendingLink(card: card, source: .view(cell)))
} }
} }
func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
MenuPreviewHelper.willPerformPreviewAction(animator: animator, presenter: self)
}
} }
extension TrendingLinksViewController { extension TrendingLinksViewController: UICollectionViewDragDelegate {
enum Section { func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
case links guard case .link(let card) = dataSource.itemIdentifier(for: indexPath),
} let url = URL(card.url) else {
struct Item: Hashable { return []
let card: Card
static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.card.url == rhs.card.url
}
func hash(into hasher: inout Hasher) {
hasher.combine(card.url)
} }
return [UIDragItem(itemProvider: NSItemProvider(object: url as NSURL))]
} }
} }

View File

@ -9,6 +9,7 @@
import UIKit import UIKit
import Pachyderm import Pachyderm
import SafariServices import SafariServices
import Combine
class TrendsViewController: UIViewController, CollectionViewController { class TrendsViewController: UIViewController, CollectionViewController {
@ -18,6 +19,8 @@ class TrendsViewController: UIViewController, CollectionViewController {
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>! private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var loadTask: Task<Void, Never>? private var loadTask: Task<Void, Never>?
private var trendingStatusesState = TrendingStatusesState.unloaded
private let confirmLoadMoreStatuses = PassthroughSubject<Void, Never>()
private var isShowingTrends = false private var isShowingTrends = false
private var shouldShowTrends: Bool { private var shouldShowTrends: Bool {
@ -42,9 +45,16 @@ class TrendsViewController: UIViewController, CollectionViewController {
let layout = UICollectionViewCompositionalLayout { [unowned self] sectionIndex, environment in let layout = UICollectionViewCompositionalLayout { [unowned self] sectionIndex, environment in
let sectionIdentifier = self.dataSource.snapshot().sectionIdentifiers[sectionIndex] let sectionIdentifier = self.dataSource.snapshot().sectionIdentifiers[sectionIndex]
switch sectionIdentifier { switch sectionIdentifier {
case .loadingIndicator:
var listConfig = UICollectionLayoutListConfiguration(appearance: .grouped)
listConfig.backgroundColor = .appGroupedBackground
listConfig.showsSeparators = false
return .list(using: listConfig, layoutEnvironment: environment)
case .trendingHashtags: case .trendingHashtags:
var listConfig = UICollectionLayoutListConfiguration(appearance: .grouped) var listConfig = UICollectionLayoutListConfiguration(appearance: .grouped)
listConfig.headerMode = .supplementary listConfig.headerMode = .supplementary
listConfig.footerMode = .supplementary
listConfig.backgroundColor = .appGroupedBackground listConfig.backgroundColor = .appGroupedBackground
return .list(using: listConfig, layoutEnvironment: environment) return .list(using: listConfig, layoutEnvironment: environment)
@ -57,9 +67,10 @@ class TrendsViewController: UIViewController, CollectionViewController {
let section = NSCollectionLayoutSection(group: group) let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .groupPaging section.orthogonalScrollingBehavior = .groupPaging
section.boundarySupplementaryItems = [ section.boundarySupplementaryItems = [
NSCollectionLayoutBoundarySupplementaryItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(12)), elementKind: UICollectionView.elementKindSectionHeader, alignment: .topLeading) NSCollectionLayoutBoundarySupplementaryItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(12)), elementKind: UICollectionView.elementKindSectionHeader, alignment: .topLeading),
NSCollectionLayoutBoundarySupplementaryItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(30)), elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottomLeading),
] ]
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 16, trailing: 0) section.contentInsets = .zero
return section return section
case .profileSuggestions: case .profileSuggestions:
@ -71,15 +82,25 @@ class TrendsViewController: UIViewController, CollectionViewController {
let section = NSCollectionLayoutSection(group: group) let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .groupPaging section.orthogonalScrollingBehavior = .groupPaging
section.boundarySupplementaryItems = [ section.boundarySupplementaryItems = [
NSCollectionLayoutBoundarySupplementaryItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(12)), elementKind: UICollectionView.elementKindSectionHeader, alignment: .topLeading) NSCollectionLayoutBoundarySupplementaryItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(12)), elementKind: UICollectionView.elementKindSectionHeader, alignment: .topLeading),
NSCollectionLayoutBoundarySupplementaryItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(30)), elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottomLeading),
] ]
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 16, trailing: 0) section.contentInsets = .zero
return section return section
case .trendingStatuses: case .trendingStatuses:
var listConfig = UICollectionLayoutListConfiguration(appearance: .grouped) var listConfig = UICollectionLayoutListConfiguration(appearance: .grouped)
listConfig.headerMode = .supplementary listConfig.headerMode = .supplementary
listConfig.backgroundColor = .appGroupedBackground listConfig.backgroundColor = .appGroupedBackground
listConfig.itemSeparatorHandler = { [unowned self] indexPath, sectionConfig in
var config = sectionConfig
if let item = dataSource.itemIdentifier(for: indexPath),
item.hideListSeparators {
config.topSeparatorVisibility = .hidden
config.bottomSeparatorVisibility = .hidden
}
return config
}
return .list(using: listConfig, layoutEnvironment: environment) return .list(using: listConfig, layoutEnvironment: environment)
} }
} }
@ -103,7 +124,23 @@ class TrendsViewController: UIViewController, CollectionViewController {
config.text = section.title config.text = section.title
headerView.contentConfiguration = config headerView.contentConfiguration = config
} }
let moreCell = UICollectionView.SupplementaryRegistration<MoreTrendsFooterCollectionViewCell>(elementKind: UICollectionView.elementKindSectionFooter) { [unowned self] supplementaryView, elementKind, indexPath in
supplementaryView.delegate = self
switch self.dataSource.sectionIdentifier(for: indexPath.section) {
case nil, .loadingIndicator, .trendingStatuses:
fatalError()
case .trendingHashtags:
supplementaryView.updateUI(.hashtags)
case .trendingLinks:
supplementaryView.updateUI(.links)
case .profileSuggestions:
supplementaryView.updateUI(.profileSuggestions)
}
}
let loadingCell = UICollectionView.CellRegistration<LoadingCollectionViewCell, Void> { cell, indexPath, itemIdentifier in
cell.indicator.startAnimating()
}
let trendingHashtagCell = UICollectionView.CellRegistration<TrendingHashtagCollectionViewCell, Hashtag> { (cell, indexPath, hashtag) in let trendingHashtagCell = UICollectionView.CellRegistration<TrendingHashtagCollectionViewCell, Hashtag> { (cell, indexPath, hashtag) in
cell.updateUI(hashtag: hashtag) cell.updateUI(hashtag: hashtag)
} }
@ -119,9 +156,16 @@ class TrendsViewController: UIViewController, CollectionViewController {
cell.delegate = self cell.delegate = self
cell.updateUI(accountID: item.0, source: item.1) cell.updateUI(accountID: item.0, source: item.1)
} }
let confirmLoadMoreCell = UICollectionView.CellRegistration<ConfirmLoadMoreCollectionViewCell, Bool> { [unowned self] cell, indexPath, isLoading in
cell.confirmLoadMore = self.confirmLoadMoreStatuses
cell.isLoading = isLoading
}
let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { collectionView, indexPath, item in let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { collectionView, indexPath, item in
switch item { switch item {
case .loadingIndicator:
return collectionView.dequeueConfiguredReusableCell(using: loadingCell, for: indexPath, item: ())
case let .tag(hashtag): case let .tag(hashtag):
return collectionView.dequeueConfiguredReusableCell(using: trendingHashtagCell, for: indexPath, item: hashtag) return collectionView.dequeueConfiguredReusableCell(using: trendingHashtagCell, for: indexPath, item: hashtag)
@ -133,11 +177,16 @@ class TrendsViewController: UIViewController, CollectionViewController {
case let .account(id, source): case let .account(id, source):
return collectionView.dequeueConfiguredReusableCell(using: accountCell, for: indexPath, item: (id, source)) return collectionView.dequeueConfiguredReusableCell(using: accountCell, for: indexPath, item: (id, source))
case let .confirmLoadMoreStatuses(loading):
return collectionView.dequeueConfiguredReusableCell(using: confirmLoadMoreCell, for: indexPath, item: loading)
} }
} }
dataSource.supplementaryViewProvider = { (collectionView, elementKind, indexPath) in dataSource.supplementaryViewProvider = { (collectionView, elementKind, indexPath) in
if elementKind == UICollectionView.elementKindSectionHeader { if elementKind == UICollectionView.elementKindSectionHeader {
return collectionView.dequeueConfiguredReusableSupplementary(using: sectionHeaderCell, for: indexPath) return collectionView.dequeueConfiguredReusableSupplementary(using: sectionHeaderCell, for: indexPath)
} else if elementKind == UICollectionView.elementKindSectionFooter {
return collectionView.dequeueConfiguredReusableSupplementary(using: moreCell, for: indexPath)
} else { } else {
return nil return nil
} }
@ -171,6 +220,11 @@ class TrendsViewController: UIViewController, CollectionViewController {
} }
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>() var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.loadingIndicator])
snapshot.appendItems([.loadingIndicator])
await apply(snapshot: snapshot)
snapshot = NSDiffableDataSourceSnapshot()
let hashtagsReq = Client.getTrendingHashtags(limit: 5) let hashtagsReq = Client.getTrendingHashtags(limit: 5)
let hashtags = try? await mastodonController.run(hashtagsReq).0 let hashtags = try? await mastodonController.run(hashtagsReq).0
@ -214,9 +268,60 @@ class TrendsViewController: UIViewController, CollectionViewController {
if !Task.isCancelled { if !Task.isCancelled {
await apply(snapshot: snapshot) await apply(snapshot: snapshot)
if snapshot.sectionIdentifiers.contains(.trendingStatuses) {
self.trendingStatusesState = .loaded
} else {
self.trendingStatusesState = .unloaded
}
} }
} }
@MainActor
private func loadOlderStatuses() async {
guard case .loaded = trendingStatusesState else {
return
}
trendingStatusesState = .loadingOlder
let origSnapshot = dataSource.snapshot()
var snapshot = origSnapshot
if Preferences.shared.disableInfiniteScrolling {
snapshot.appendItems([.confirmLoadMoreStatuses(false)], toSection: .trendingStatuses)
await apply(snapshot: snapshot)
for await _ in confirmLoadMoreStatuses.values {
break
}
snapshot.deleteItems([.confirmLoadMoreStatuses(false)])
snapshot.appendItems([.confirmLoadMoreStatuses(true)], toSection: .trendingStatuses)
await apply(snapshot: snapshot, animatingDifferences: false)
} else {
snapshot.appendItems([.loadingIndicator], toSection: .trendingStatuses)
await apply(snapshot: snapshot)
}
do {
let request = Client.getTrendingStatuses(offset: origSnapshot.itemIdentifiers(inSection: .trendingStatuses).count)
let (statuses, _) = try await mastodonController.run(request)
await mastodonController.persistentContainer.addAll(statuses: statuses)
var snapshot = origSnapshot
snapshot.appendItems(statuses.map { .status($0.id, .unknown) }, toSection: .trendingStatuses)
await apply(snapshot: snapshot)
} catch {
await apply(snapshot: origSnapshot)
let config = ToastConfiguration(from: error, with: "Error Loading More Trending Statuses", in: self) { [weak self] toast in
toast.dismissToast(animated: true)
await self?.loadOlderStatuses()
}
showToast(configuration: config, animated: true)
}
trendingStatusesState = .loaded
}
@objc private func preferencesChanged() { @objc private func preferencesChanged() {
if isShowingTrends != shouldShowTrends { if isShowingTrends != shouldShowTrends {
loadTask?.cancel() loadTask?.cancel()
@ -226,9 +331,9 @@ class TrendsViewController: UIViewController, CollectionViewController {
} }
} }
private func apply(snapshot: NSDiffableDataSourceSnapshot<Section, Item>) async { private func apply(snapshot: NSDiffableDataSourceSnapshot<Section, Item>, animatingDifferences: Bool = true) async {
await Task { @MainActor in await Task { @MainActor in
self.dataSource.apply(snapshot) self.dataSource.apply(snapshot, animatingDifferences: animatingDifferences)
}.value }.value
} }
@ -251,15 +356,26 @@ class TrendsViewController: UIViewController, CollectionViewController {
} }
} }
extension TrendsViewController {
enum TrendingStatusesState {
case unloaded
case loaded
case loadingOlder
}
}
extension TrendsViewController { extension TrendsViewController {
enum Section { enum Section {
case loadingIndicator
case trendingHashtags case trendingHashtags
case trendingLinks case trendingLinks
case profileSuggestions case profileSuggestions
case trendingStatuses case trendingStatuses
var title: String { var title: String? {
switch self { switch self {
case .loadingIndicator:
return nil
case .trendingHashtags: case .trendingHashtags:
return "Trending Hashtags" return "Trending Hashtags"
case .trendingLinks: case .trendingLinks:
@ -272,13 +388,17 @@ extension TrendsViewController {
} }
} }
enum Item: Equatable, Hashable { enum Item: Equatable, Hashable {
case loadingIndicator
case status(String, CollapseState) case status(String, CollapseState)
case tag(Hashtag) case tag(Hashtag)
case link(Card) case link(Card)
case account(String, Suggestion.Source) case account(String, Suggestion.Source)
case confirmLoadMoreStatuses(Bool)
static func == (lhs: Item, rhs: Item) -> Bool { static func == (lhs: Item, rhs: Item) -> Bool {
switch (lhs, rhs) { switch (lhs, rhs) {
case (.loadingIndicator, .loadingIndicator):
return true
case let (.status(a, _), .status(b, _)): case let (.status(a, _), .status(b, _)):
return a == b return a == b
case let (.tag(a), .tag(b)): case let (.tag(a), .tag(b)):
@ -287,6 +407,8 @@ extension TrendsViewController {
return a.url == b.url return a.url == b.url
case let (.account(a, _), .account(b, _)): case let (.account(a, _), .account(b, _)):
return a == b return a == b
case (.confirmLoadMoreStatuses(let a), .confirmLoadMoreStatuses(let b)):
return a == b
default: default:
return false return false
} }
@ -294,6 +416,8 @@ extension TrendsViewController {
func hash(into hasher: inout Hasher) { func hash(into hasher: inout Hasher) {
switch self { switch self {
case .loadingIndicator:
hasher.combine("loadingIndicator")
case let .status(id, _): case let .status(id, _):
hasher.combine("status") hasher.combine("status")
hasher.combine(id) hasher.combine(id)
@ -306,17 +430,54 @@ extension TrendsViewController {
case let .account(id, _): case let .account(id, _):
hasher.combine("account") hasher.combine("account")
hasher.combine(id) hasher.combine(id)
case let .confirmLoadMoreStatuses(loading):
hasher.combine("confirmLoadMoreStatuses")
hasher.combine(loading)
}
}
var shouldSelect: Bool {
switch self {
case .loadingIndicator, .confirmLoadMoreStatuses(_):
return false
default:
return true
}
}
var hideListSeparators: Bool {
switch self {
case .loadingIndicator, .confirmLoadMoreStatuses(_):
return true
default:
return false
} }
} }
} }
} }
extension TrendsViewController: UICollectionViewDelegate { extension TrendsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if case .trendingStatuses = dataSource.sectionIdentifier(for: indexPath.section),
indexPath.row == collectionView.numberOfItems(inSection: indexPath.section) - 1 {
Task {
await self.loadOlderStatuses()
}
}
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return dataSource.itemIdentifier(for: indexPath)?.shouldSelect ?? false
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath) else { guard let item = dataSource.itemIdentifier(for: indexPath) else {
return return
} }
switch item { switch item {
case .loadingIndicator, .confirmLoadMoreStatuses(_):
return
case let .tag(hashtag): case let .tag(hashtag):
show(HashtagTimelineViewController(for: hashtag, mastodonController: mastodonController), sender: nil) show(HashtagTimelineViewController(for: hashtag, mastodonController: mastodonController), sender: nil)
@ -340,6 +501,9 @@ extension TrendsViewController: UICollectionViewDelegate {
} }
switch item { switch item {
case .loadingIndicator, .confirmLoadMoreStatuses(_):
return nil
case let .tag(hashtag): case let .tag(hashtag):
return UIContextMenuConfiguration(identifier: nil) { return UIContextMenuConfiguration(identifier: nil) {
HashtagTimelineViewController(for: hashtag, mastodonController: self.mastodonController) HashtagTimelineViewController(for: hashtag, mastodonController: self.mastodonController)
@ -351,12 +515,13 @@ extension TrendsViewController: UICollectionViewDelegate {
guard let url = URL(card.url) else { guard let url = URL(card.url) else {
return nil return nil
} }
let cell = collectionView.cellForItem(at: indexPath)!
return UIContextMenuConfiguration { return UIContextMenuConfiguration {
let vc = SFSafariViewController(url: url) let vc = SFSafariViewController(url: url)
vc.preferredControlTintColor = Preferences.shared.accentColor.color vc.preferredControlTintColor = Preferences.shared.accentColor.color
return vc return vc
} actionProvider: { _ in } actionProvider: { _ in
UIMenu(children: self.actionsForTrendingLink(card: card)) UIMenu(children: self.actionsForTrendingLink(card: card, source: .view(cell)))
} }
case let .status(id, state): case let .status(id, state):
@ -424,6 +589,9 @@ extension TrendsViewController: UICollectionViewDragDelegate {
return [] return []
} }
switch item { switch item {
case .loadingIndicator, .confirmLoadMoreStatuses(_):
return []
case let .tag(hashtag): case let .tag(hashtag):
guard let url = URL(hashtag.url) else { guard let url = URL(hashtag.url) else {
return [] return []

View File

@ -346,12 +346,16 @@ extension MenuActionProvider {
} }
} }
func actionsForTrendingLink(card: Card) -> [UIMenuElement] { func actionsForTrendingLink(card: Card, source: PopoverSource) -> [UIMenuElement] {
guard let url = URL(card.url) else { guard let url = URL(card.url) else {
return [] return []
} }
return [ return [
openInSafariAction(url: url), openInSafariAction(url: url),
createAction(identifier: "share", title: "Share", systemImageName: "square.and.arrow.up", handler: { [weak self] (_) in
guard let self else { return }
self.navigationDelegate?.showMoreOptions(forURL: url, source: source)
}),
createAction(identifier: "postlink", title: "Post this Link", systemImageName: "square.and.pencil", handler: { [weak self] _ in createAction(identifier: "postlink", title: "Post this Link", systemImageName: "square.and.pencil", handler: { [weak self] _ in
guard let self = self else { return } guard let self = self else { return }
let draft = self.mastodonController!.createDraft() let draft = self.mastodonController!.createDraft()

View File

@ -28,7 +28,7 @@ class ConfirmLoadMoreCollectionViewCell: UICollectionViewCell {
override init(frame: CGRect) { override init(frame: CGRect) {
super.init(frame: frame) super.init(frame: frame)
backgroundColor = .systemGroupedBackground backgroundColor = .appGroupedBackground
let label = UILabel() let label = UILabel()
label.text = "Infinite scrolling is off. Do you want to keep going?" label.text = "Infinite scrolling is off. Do you want to keep going?"