Tusker/Tusker/Screens/Explore/TrendingStatusesViewControl...

94 lines
2.8 KiB
Swift

//
// TrendingStatusesViewController.swift
// Tusker
//
// Created by Shadowfacts on 4/1/22.
// Copyright © 2022 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
class TrendingStatusesViewController: 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 Posts", comment: "trending posts screen title")
tableView.register(UINib(nibName: "TimelineStatusTableViewCell", bundle: .main), forCellReuseIdentifier: "statusCell")
tableView.estimatedRowHeight = 144
dataSource = UITableViewDiffableDataSource(tableView: tableView, cellProvider: { tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "statusCell", for: indexPath) as! TimelineStatusTableViewCell
cell.delegate = self
cell.updateUI(statusID: item.id, state: item.state)
return cell
})
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let request = Client.getTrendingStatuses()
Task {
guard let (statuses, _) = try? await mastodonController.run(request) else {
return
}
mastodonController.persistentContainer.addAll(statuses: statuses) {
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.statuses])
snapshot.appendItems(statuses.map { Item(id: $0.id, state: .unknown) })
self.dataSource.apply(snapshot)
}
}
}
// MARK: - Table View Delegate
}
extension TrendingStatusesViewController {
enum Section {
case statuses
}
struct Item: Hashable {
let id: String
let state: StatusState
static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
}
extension TrendingStatusesViewController: TuskerNavigationDelegate {
var apiController: MastodonController { mastodonController }
}
extension TrendingStatusesViewController: StatusTableViewCellDelegate {
func statusCellCollapsedStateChanged(_ cell: BaseStatusTableViewCell) {
tableView.beginUpdates()
tableView.endUpdates()
}
}