Use cards for trending links screen, and add pagination

See #355
This commit is contained in:
Shadowfacts 2023-02-11 10:09:56 -05:00
parent d8c7eb5cf5
commit ea85b11945
5 changed files with 256 additions and 55 deletions

View File

@ -437,12 +437,13 @@ public class Client {
return Request(method: .get, path: "/api/v1/trends/statuses", queryParameters: parameters)
}
public static func getTrendingLinks(limit: Int? = nil) -> Request<[Card]> {
let parameters: [Parameter]
if let limit = limit {
parameters = ["limit" => limit]
} else {
parameters = []
public static func getTrendingLinks(limit: Int? = nil, offset: Int? = nil) -> Request<[Card]> {
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/links", queryParameters: parameters)
}

View File

@ -21,6 +21,29 @@ class TrendingLinkCardCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var providerLabel: UILabel!
@IBOutlet weak var activityLabel: UILabel!
@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?
@ -37,6 +60,8 @@ class TrendingLinkCardCollectionViewCell: UICollectionViewCell {
contentView.backgroundColor = .appGroupedCellBackground
updateLayerColors()
verticalSize = .regular
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">
<rect key="frame" x="0.0" y="0.0" width="300" height="225"/>
<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>
</imageView>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" alignment="top" spacing="4" translatesAutoresizingMaskIntoConstraints="NO" id="LpU-m4-guC">
@ -56,9 +56,9 @@
</constraints>
</view>
<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">
<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"/>
<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">

View File

@ -10,19 +10,22 @@ import UIKit
import Pachyderm
import WebURLFoundationExtras
import SafariServices
import Combine
class TrendingLinksViewController: EnhancedTableViewController {
class TrendingLinksViewController: UIViewController, CollectionViewController {
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) {
self.mastodonController = mastodonController
super.init(style: .grouped)
dragEnabled = true
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
@ -34,73 +37,239 @@ class TrendingLinksViewController: EnhancedTableViewController {
title = NSLocalizedString("Trending Links", comment: "trending links screen title")
tableView.register(TrendingLinkTableViewCell.self, forCellReuseIdentifier: "trendingLinkCell")
tableView.estimatedRowHeight = 100
tableView.allowsFocus = true
tableView.backgroundColor = .appGroupedBackground
let layout = UICollectionViewCompositionalLayout { [unowned self] sectionIndex, environment in
switch dataSource.sectionIdentifier(for: sectionIndex) {
case nil:
fatalError()
case .loadingIndicator, .confirmLoadMore:
var config = UICollectionLayoutListConfiguration(appearance: .grouped)
config.backgroundColor = .appGroupedBackground
config.showsSeparators = false
let section = NSCollectionLayoutSection.list(using: config, layoutEnvironment: environment)
if UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac {
section.contentInsetsReference = .readableContent
}
return section
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
let cell = tableView.dequeueReusableCell(withIdentifier: "trendingLinkCell", for: indexPath) as! TrendingLinkTableViewCell
cell.updateUI(card: item.card)
return cell
})
dataSource = createDataSource()
}
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) {
super.viewWillAppear(animated)
let request = Client.getTrendingLinks()
Task {
guard let (links, _) = try? await mastodonController.run(request) else {
return
}
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.links])
snapshot.appendItems(links.map(Item.init))
await dataSource.apply(snapshot)
await loadInitial()
}
}
// 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)
let request = Client.getTrendingLinks()
guard let (links, _) = try? await mastodonController.run(request) else {
return
}
snapshot.deleteSections([.loadingIndicator])
snapshot.appendSections([.links])
snapshot.appendItems(links.map { .link($0) })
await dataSource.apply(snapshot)
state = .loaded
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath),
let url = URL(item.card.url) else {
@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.appendSections([.confirmLoadMore])
snapshot.appendItems([.confirmLoadMore(false)], toSection: .confirmLoadMore)
await dataSource.apply(snapshot)
for await _ in confirmLoadMore.values {
break
}
snapshot.deleteItems([.confirmLoadMore(false)])
snapshot.appendItems([.confirmLoadMore(true)], toSection: .confirmLoadMore)
await dataSource.apply(snapshot, animatingDifferences: false)
} else {
snapshot.appendSections([.loadingIndicator])
snapshot.appendItems([.loadingIndicator], toSection: .confirmLoadMore)
await dataSource.apply(snapshot)
}
let request = Client.getTrendingLinks(offset: snapshot.itemIdentifiers.count)
guard let (links, _) = try? await mastodonController.run(request) else {
return
}
snapshot = origSnapshot
snapshot.appendItems(links.map { .link($0) }, toSection: .links)
await dataSource.apply(snapshot)
state = .loaded
}
}
extension TrendingLinksViewController {
enum State {
case unloaded
case loading
case loaded
case loadingOlder
}
}
extension TrendingLinksViewController {
enum Section {
case loadingIndicator
case links
case confirmLoadMore
}
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)
}
}
}
}
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, didSelectItemAt indexPath: IndexPath) {
guard case .link(let card) = dataSource.itemIdentifier(for: indexPath),
let url = URL(card.url) else {
return
}
selected(url: url)
}
override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
guard let item = dataSource.itemIdentifier(for: indexPath),
let url = URL(item.card.url) else {
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
guard case .link(let card) = dataSource.itemIdentifier(for: indexPath),
let url = URL(card.url) else {
return nil
}
return UIContextMenuConfiguration(identifier: nil) {
return UIContextMenuConfiguration {
let vc = SFSafariViewController(url: url)
vc.preferredControlTintColor = Preferences.shared.accentColor.color
return vc
} actionProvider: { _ in
return UIMenu(children: self.actionsForTrendingLink(card: item.card))
UIMenu(children: self.actionsForTrendingLink(card: card))
}
}
func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
MenuPreviewHelper.willPerformPreviewAction(animator: animator, presenter: self)
}
}
extension TrendingLinksViewController {
enum Section {
case links
}
struct Item: Hashable {
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)
extension TrendingLinksViewController: UICollectionViewDragDelegate {
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
guard case .link(let card) = dataSource.itemIdentifier(for: indexPath),
let url = URL(card.url) else {
return []
}
return [UIDragItem(itemProvider: NSItemProvider(object: url as NSURL))]
}
}

View File

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