Tusker/Tusker/Screens/Profile/NewProfileStatusesViewContr...

328 lines
11 KiB
Swift

//
// NewProfileStatusesViewController.swift
// Tusker
//
// Created by Shadowfacts on 10/6/22.
// Copyright © 2022 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
import Combine
class NewProfileStatusesViewController: UIViewController, TimelineLikeCollectionViewController {
weak var mastodonController: MastodonController!
var accountID: String!
let kind: Kind
private(set) var controller: TimelineLikeController<TimelineItem>!
let confirmLoadMore = PassthroughSubject<Void, Never>()
private var newer: RequestRange?
private var older: RequestRange?
var collectionView: UICollectionView {
view as! UICollectionView
}
private(set) var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
init(accountID: String?, kind: Kind, mastodonController: MastodonController) {
self.accountID = accountID
self.kind = kind
self.mastodonController = mastodonController
super.init(nibName: nil, bundle: nil)
self.controller = TimelineLikeController(delegate: self)
// TODO: refresh key command
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
var config = UICollectionLayoutListConfiguration(appearance: .plain)
config.leadingSwipeActionsConfigurationProvider = { [unowned self] in
(collectionView.cellForItem(at: $0) as? TimelineStatusCollectionViewCell)?.leadingSwipeActions()
}
config.trailingSwipeActionsConfigurationProvider = { [unowned self] in
(collectionView.cellForItem(at: $0) as? TimelineStatusCollectionViewCell)?.trailingSwipeActions()
}
// TODO: item separators
let layout = UICollectionViewCompositionalLayout.list(using: config)
view = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.delegate = self
// TODO: drag delegate
registerTimelineLikeCells()
dataSource = createDataSource()
applyInitialSnapshot()
// TODO: refresh control
}
override func viewDidLoad() {
super.viewDidLoad()
}
private func createDataSource() -> UICollectionViewDiffableDataSource<Section, Item> {
let statusCell = UICollectionView.CellRegistration<TimelineStatusCollectionViewCell, (String, StatusState, Bool)> { [unowned self] cell, indexPath, item in
cell.delegate = self
cell.showPinned = item.2
cell.updateUI(statusID: item.0, state: item.1)
}
return UICollectionViewDiffableDataSource(collectionView: collectionView) { [unowned self] collectionView, indexPath, itemIdentifier in
switch itemIdentifier {
case .status(id: let id, state: let state, pinned: let pinned):
return collectionView.dequeueConfiguredReusableCell(using: statusCell, for: indexPath, item: (id, state, pinned))
case .loadingIndicator:
return loadingIndicatorCell(for: indexPath)
case .confirmLoadMore:
return confirmLoadMoreCell(for: indexPath)
}
}
}
private func applyInitialSnapshot() {
// TODO: header
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView.indexPathsForSelectedItems?.forEach {
collectionView.deselectItem(at: $0, animated: true)
}
Task {
await controller.loadInitial()
await tryLoadPinned()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// TODO: prune offscreen rows
}
// TODO: refreshing
private func tryLoadPinned() async {
do {
try await loadPinned()
} catch {
let config = ToastConfiguration(from: error, with: "Loading Pinned", in: self) { toast in
toast.dismissToast(animated: true)
Task {
await self.tryLoadPinned()
}
}
self.showToast(configuration: config, animated: true)
}
}
private func loadPinned() async throws {
guard case .statuses = kind,
mastodonController.instanceFeatures.profilePinnedStatuses else {
return
}
let request = Account.getStatuses(accountID, range: .default, onlyMedia: false, pinned: true, excludeReplies: false)
let (statuses, _) = try await mastodonController.run(request)
await withCheckedContinuation { continuation in
mastodonController.persistentContainer.addAll(statuses: statuses) {
continuation.resume()
}
}
var snapshot = dataSource.snapshot()
if !snapshot.sectionIdentifiers.contains(.pinned) {
if snapshot.sectionIdentifiers.isEmpty {
snapshot.appendSections([.pinned])
} else {
snapshot.insertSections([.pinned], beforeSection: snapshot.sectionIdentifiers.first!)
}
}
let items = statuses.map { Item.status(id: $0.id, state: .unknown, pinned: true) }
snapshot.appendItems(items, toSection: .pinned)
await apply(snapshot, animatingDifferences: true)
}
}
extension NewProfileStatusesViewController {
enum Kind {
case statuses, withReplies, onlyMedia
}
}
extension NewProfileStatusesViewController {
enum Section: TimelineLikeCollectionViewSection {
case pinned
case statuses
case footer
static var entries: Self { .statuses }
}
enum Item: TimelineLikeCollectionViewItem {
typealias TimelineItem = String
case status(id: String, state: StatusState, pinned: Bool)
case loadingIndicator
case confirmLoadMore
static func fromTimelineItem(_ item: String) -> Self {
return .status(id: item, state: .unknown, pinned: false)
}
static func ==(lhs: Item, rhs: Item) -> Bool {
switch (lhs, rhs) {
case let (.status(id: a, state: _, pinned: ap), .status(id: b, state: _, pinned: bp)):
return a == b && ap == bp
case (.loadingIndicator, .loadingIndicator):
return true
case (.confirmLoadMore, .confirmLoadMore):
return true
default:
return false
}
}
func hash(into hasher: inout Hasher) {
switch self {
case .status(id: let id, state: _, pinned: let pinned):
hasher.combine(0)
hasher.combine(id)
hasher.combine(pinned)
case .loadingIndicator:
hasher.combine(1)
case .confirmLoadMore:
hasher.combine(2)
}
}
}
}
extension NewProfileStatusesViewController: TimelineLikeControllerDelegate {
typealias TimelineItem = String // status ID
private func request(for range: RequestRange = .default) -> Request<[Status]> {
switch kind {
case .statuses:
return Account.getStatuses(accountID, range: range, onlyMedia: false, pinned: false, excludeReplies: true)
case .withReplies:
return Account.getStatuses(accountID, range: range, onlyMedia: false, pinned: false, excludeReplies: false)
case .onlyMedia:
return Account.getStatuses(accountID, range: range, onlyMedia: true, pinned: false, excludeReplies: false)
}
}
func loadInitial() async throws -> [String] {
guard let mastodonController else {
throw Error.noClient
}
let request = request()
let (statuses, _) = try await mastodonController.run(request)
if !statuses.isEmpty {
newer = .after(id: statuses.first!.id, count: nil)
older = .before(id: statuses.last!.id, count: nil)
}
return await withCheckedContinuation { continuation in
mastodonController.persistentContainer.addAll(statuses: statuses) {
continuation.resume(returning: statuses.map(\.id))
}
}
}
func loadNewer() async throws -> [String] {
guard let newer else {
throw Error.noNewer
}
let request = request(for: newer)
let (statuses, _) = try await mastodonController.run(request)
guard !statuses.isEmpty else {
throw Error.allCaughtUp
}
self.newer = .after(id: statuses.first!.id, count: nil)
return await withCheckedContinuation { continuation in
mastodonController.persistentContainer.addAll(statuses: statuses) {
continuation.resume(returning: statuses.map(\.id))
}
}
}
func loadOlder() async throws -> [String] {
guard let older else {
throw Error.noOlder
}
let request = request(for: older)
let (statuses, _) = try await mastodonController.run(request)
guard !statuses.isEmpty else {
return []
}
self.older = .before(id: statuses.last!.id, count: nil)
return await withCheckedContinuation { continuation in
mastodonController.persistentContainer.addAll(statuses: statuses) {
continuation.resume(returning: statuses.map(\.id))
}
}
}
enum Error: TimelineLikeCollectionViewError {
case noClient
case noNewer
case noOlder
case allCaughtUp
}
}
extension NewProfileStatusesViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard case .statuses = dataSource.sectionIdentifier(for: indexPath.section) else {
return
}
let itemsInSection = collectionView.numberOfItems(inSection: indexPath.section)
if indexPath.row == itemsInSection - 1 {
Task {
await controller.loadOlder()
}
}
}
// TODO: cell selection
}
extension NewProfileStatusesViewController: TuskerNavigationDelegate {
var apiController: MastodonController { mastodonController }
}
extension NewProfileStatusesViewController: MenuActionProvider {
}
extension NewProfileStatusesViewController: StatusCollectionViewCellDelegate {
func statusCellNeedsReconfigure(_ cell: StatusCollectionViewCell, animated: Bool, completion: (() -> Void)?) {
if let indexPath = collectionView.indexPath(for: cell) {
var snapshot = dataSource.snapshot()
snapshot.reconfigureItems([dataSource.itemIdentifier(for: indexPath)!])
dataSource.apply(snapshot, animatingDifferences: false, completion: completion)
}
}
}