Convert ProfileStatusesViewController to DiffableTimelineLike

This commit is contained in:
Shadowfacts 2021-11-25 12:27:59 -05:00
parent 777d1f378c
commit 654b5d9c59
3 changed files with 129 additions and 125 deletions

View File

@ -9,7 +9,7 @@
import UIKit import UIKit
import Pachyderm import Pachyderm
class ProfileStatusesViewController: TimelineLikeTableViewController<TimelineEntry> { class ProfileStatusesViewController: DiffableTimelineLikeTableViewController<ProfileStatusesViewController.Section, ProfileStatusesViewController.Item> {
weak var mastodonController: MastodonController! weak var mastodonController: MastodonController!
@ -43,50 +43,50 @@ class ProfileStatusesViewController: TimelineLikeTableViewController<TimelineEnt
} }
func updateUI(account: AccountMO) { func updateUI(account: AccountMO) {
loadInitial() if isViewLoaded {
reloadInitial()
}
} }
override class func refreshCommandTitle() -> String { override class func refreshCommandTitle() -> String {
return NSLocalizedString("Refresh Statuses", comment: "refresh statuses command discoverability title") return NSLocalizedString("Refresh Statuses", comment: "refresh statuses command discoverability title")
} }
override func headerSectionsCount() -> Int { override func cellProvider(_ tableView: UITableView, _ indexPath: IndexPath, _ item: Item) -> UITableViewCell? {
return 1 let cell = tableView.dequeueReusableCell(withIdentifier: "statusCell", for: indexPath) as! TimelineStatusTableViewCell
cell.delegate = self
// todo: dataSource.sectionIdentifier is only available on iOS 15
cell.showPinned = dataSource.snapshot().indexOfSection(.pinned) == indexPath.section
cell.updateUI(statusID: item.id, state: item.state)
return cell
} }
override func loadInitial() { override func loadInitialItems(completion: @escaping (LoadResult) -> Void) {
guard accountID != nil else { guard accountID != nil else {
completion(.failure(.noClient))
return return
} }
if !loaded { getStatuses { (response) in
loadPinnedStatuses() switch response {
} case let .failure(error):
completion(.failure(.client(error)))
super.loadInitial()
} case let .success(statuses, pagination):
self.older = pagination?.older
private func loadPinnedStatuses() { self.newer = pagination?.newer
guard kind == .statuses else {
return self.mastodonController.persistentContainer.addAll(statuses: statuses) {
} DispatchQueue.main.async {
getPinnedStatuses { (response) in var snapshot = self.dataSource.snapshot()
guard case let .success(statuses, _) = response, snapshot.appendSections([.statuses])
!statuses.isEmpty else { snapshot.appendItems(statuses.map { Item(id: $0.id, state: .unknown) }, toSection: .statuses)
// todo: error message if self.kind == .statuses {
return self.loadPinnedStatuses(snapshot: { snapshot }, completion: completion)
}
self.mastodonController.persistentContainer.addAll(statuses: statuses) {
let items = statuses.map { ($0.id, StatusState.unknown) }
DispatchQueue.main.async {
UIView.performWithoutAnimation {
if self.sections.count < 1 {
self.sections.append(items)
self.tableView.insertSections(IndexSet(integer: 0), with: .none)
} else { } else {
self.sections[0] = items completion(.success(snapshot))
self.tableView.reloadSections(IndexSet(integer: 0), with: .none)
} }
} }
} }
@ -94,64 +94,94 @@ class ProfileStatusesViewController: TimelineLikeTableViewController<TimelineEnt
} }
} }
override func loadInitialItems(completion: @escaping ([TimelineEntry]) -> Void) { private func loadPinnedStatuses(snapshot: @escaping () -> Snapshot, completion: @escaping (LoadResult) -> Void) {
getStatuses { (response) in guard kind == .statuses else {
guard case let .success(statuses, pagination) = response, completion(.success(snapshot()))
!statuses.isEmpty else { return
// todo: error message }
completion([]) getPinnedStatuses { (response) in
return switch response {
} case let .failure(error):
completion(.failure(.client(error)))
self.older = pagination?.older
self.newer = pagination?.newer case let .success(statuses, _):
self.mastodonController.persistentContainer.addAll(statuses: statuses) {
self.mastodonController.persistentContainer.addAll(statuses: statuses) { DispatchQueue.main.async {
completion(statuses.map { ($0.id, .unknown) }) var snapshot = snapshot()
if snapshot.indexOfSection(.pinned) != nil {
snapshot.deleteSections([.pinned])
}
snapshot.insertSections([.pinned], beforeSection: .statuses)
snapshot.appendItems(statuses.map { Item(id: $0.id, state: .unknown) }, toSection: .pinned)
completion(.success(snapshot))
}
}
} }
} }
} }
override func loadOlder(completion: @escaping ([TimelineEntry]) -> Void) { override func loadOlderItems(currentSnapshot: @escaping () -> Snapshot, completion: @escaping (LoadResult) -> Void) {
guard let older = older else { guard let older = older else {
completion([]) completion(.failure(.noOlder))
return return
} }
getStatuses(for: older) { (response) in getStatuses(for: older) { (response) in
guard case let .success(statuses, pagination) = response else { switch response {
// todo: error message case let .failure(error):
completion([]) completion(.failure(.client(error)))
return
} case let .success(statuses, pagination):
guard !statuses.isEmpty else {
self.older = pagination?.older completion(.failure(.noOlder))
return
self.mastodonController.persistentContainer.addAll(statuses: statuses) { }
completion(statuses.map { ($0.id, .unknown) })
if let older = pagination?.older {
self.older = older
}
self.mastodonController.persistentContainer.addAll(statuses: statuses) {
var snapshot = currentSnapshot()
snapshot.appendItems(statuses.map { Item(id: $0.id, state: .unknown) }, toSection: .statuses)
completion(.success(snapshot))
}
} }
} }
} }
override func loadNewer(completion: @escaping ([TimelineEntry]) -> Void) { override func loadNewerItems(currentSnapshot: @escaping () -> Snapshot, completion: @escaping (LoadResult) -> Void) {
guard let newer = newer else { guard let newer = newer else {
completion([]) completion(.failure(.noNewer))
return return
} }
getStatuses(for: newer) { (response) in getStatuses(for: newer) { (response) in
guard case let .success(statuses, pagination) = response else { switch response {
// todo: error message case let .failure(error):
completion([]) completion(.failure(.client(error)))
return
} case let .success(statuses, pagination):
guard !statuses.isEmpty else {
if let newer = pagination?.newer { completion(.failure(.noNewer))
self.newer = newer return
} }
self.mastodonController.persistentContainer.addAll(statuses: statuses) { if let newer = pagination?.newer {
completion(statuses.map { ($0.id, .unknown) }) self.newer = newer
}
self.mastodonController.persistentContainer.addAll(statuses: statuses) {
var snapshot = currentSnapshot()
let items = statuses.map { Item(id: $0.id, state: .unknown) }
if let first = snapshot.itemIdentifiers(inSection: .statuses).first {
snapshot.insertItems(items, beforeItem: first)
} else {
snapshot.appendItems(items, toSection: .statuses)
}
completion(.success(snapshot))
}
} }
} }
} }
@ -178,53 +208,20 @@ class ProfileStatusesViewController: TimelineLikeTableViewController<TimelineEnt
super.refresh() super.refresh()
if kind == .statuses { if kind == .statuses {
getPinnedStatuses { (response) in loadPinnedStatuses(snapshot: dataSource.snapshot) { (result) in
guard case let .success(newPinnedStatues, _) = response else { switch result {
// todo: error message case .failure(_):
return break
}
case let .success(snapshot):
self.mastodonController.persistentContainer.addAll(statuses: newPinnedStatues) {
// if the user refreshes before the initial pinned statuses request completes, self.sections will be empty
let oldPinnedStatuses = self.sections.isEmpty ? [] : self.sections[0]
let pinnedStatues = newPinnedStatues.map { (status) -> TimelineEntry in
let state: StatusState
if let (_, oldState) = oldPinnedStatuses.first(where: { $0.id == status.id }) {
state = oldState
} else {
state = .unknown
}
return (status.id, state)
}
DispatchQueue.main.async { DispatchQueue.main.async {
UIView.performWithoutAnimation { self.dataSource.apply(snapshot)
if self.sections.count < 1 {
self.sections.append(pinnedStatues)
self.tableView.insertSections(IndexSet(integer: 0), with: .none)
} else {
self.sections[0] = pinnedStatues
self.tableView.reloadSections(IndexSet(integer: 0), with: .none)
}
}
} }
} }
} }
} }
} }
// MARK: - UITableViewDatasource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "statusCell", for: indexPath) as! TimelineStatusTableViewCell
cell.delegate = self
cell.showPinned = indexPath.section == 0
let (id, state) = item(for: indexPath)
cell.updateUI(statusID: id, state: state)
return cell
}
} }
extension ProfileStatusesViewController { extension ProfileStatusesViewController {
@ -233,6 +230,17 @@ extension ProfileStatusesViewController {
} }
} }
extension ProfileStatusesViewController {
enum Section: CaseIterable {
case pinned
case statuses
}
struct Item: Hashable {
let id: String
let state: StatusState
}
}
extension ProfileStatusesViewController: TuskerNavigationDelegate { extension ProfileStatusesViewController: TuskerNavigationDelegate {
var apiController: MastodonController { mastodonController } var apiController: MastodonController { mastodonController }
} }
@ -245,18 +253,12 @@ extension ProfileStatusesViewController: StatusTableViewCellDelegate {
extension ProfileStatusesViewController: UITableViewDataSourcePrefetching, StatusTablePrefetching { extension ProfileStatusesViewController: UITableViewDataSourcePrefetching, StatusTablePrefetching {
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
let ids = indexPaths.map { item(for: $0).id } let ids = indexPaths.compactMap { dataSource.itemIdentifier(for: $0)?.id }
prefetchStatuses(with: ids) prefetchStatuses(with: ids)
} }
func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) { func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) {
let ids: [String] = indexPaths.compactMap { let ids = indexPaths.compactMap { dataSource.itemIdentifier(for: $0)?.id }
guard $0.section < sections.count,
$0.row < sections[$0.section].count else {
return nil
}
return item(for: $0).id
}
cancelPrefetchingStatuses(with: ids) cancelPrefetchingStatuses(with: ids)
} }
} }

View File

@ -211,9 +211,8 @@ class ProfileViewController: UIPageViewController {
// Layout and update the table view, otherwise the content jumps around when first scrolling it, // Layout and update the table view, otherwise the content jumps around when first scrolling it,
// if old was not scrolled all the way to the top // if old was not scrolled all the way to the top
new.tableView.layoutIfNeeded() new.tableView.layoutIfNeeded()
UIView.performWithoutAnimation { let snapshot = new.dataSource.snapshot()
new.tableView.performBatchUpdates(nil, completion: nil) new.dataSource.apply(snapshot, animatingDifferences: false)
}
completion?(finished) completion?(finished)
} }

View File

@ -88,7 +88,10 @@ class DiffableTimelineLikeTableViewController<Section: Hashable & CaseIterable,
let sectionsToRemove = contentSections[lastVisibleContentSectionIndex...] let sectionsToRemove = contentSections[lastVisibleContentSectionIndex...]
snapshot.deleteSections(Array(sectionsToRemove)) snapshot.deleteSections(Array(sectionsToRemove))
willRemoveItems(sectionsToRemove.flatMap(snapshot.itemIdentifiers(inSection:))) let itemsToRemove = sectionsToRemove.filter {
snapshot.indexOfSection($0) != nil
}.flatMap(snapshot.itemIdentifiers(inSection:))
willRemoveItems(itemsToRemove)
} else if lastVisibleContentSectionIndex == contentSections.count - 1 { } else if lastVisibleContentSectionIndex == contentSections.count - 1 {
let items = snapshot.itemIdentifiers(inSection: lastVisibleRowSection) let items = snapshot.itemIdentifiers(inSection: lastVisibleRowSection)