Tusker/Tusker/Screens/Explore/TrendingLinksViewController...

114 lines
3.5 KiB
Swift

//
// TrendingLinksViewController.swift
// Tusker
//
// Created by Shadowfacts on 4/2/22.
// Copyright © 2022 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
import WebURLFoundationExtras
import SafariServices
class TrendingLinksViewController: EnhancedTableViewController {
weak var mastodonController: MastodonController!
private var dataSource: UITableViewDiffableDataSource<Section, Item>!
init(mastodonController: MastodonController) {
self.mastodonController = mastodonController
super.init(style: .grouped)
dragEnabled = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Trending Links", comment: "trending links screen title")
tableView.register(TrendingLinkTableViewCell.self, forCellReuseIdentifier: "trendingLinkCell")
tableView.estimatedRowHeight = 100
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
})
}
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)
}
}
// MARK: - Table View Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath),
let url = URL(item.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 {
return nil
}
return UIContextMenuConfiguration(identifier: nil) {
let vc = SFSafariViewController(url: url)
vc.preferredControlTintColor = Preferences.shared.accentColor.color
return vc
} actionProvider: { _ in
return UIMenu(children: self.actionsForTrendingLink(card: item.card))
}
}
}
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: TuskerNavigationDelegate {
var apiController: MastodonController! { mastodonController }
}
extension TrendingLinksViewController: ToastableViewController {
}
extension TrendingLinksViewController: MenuActionProvider {
}