Tusker/Tusker/Screens/Lists/EditListAccountsViewControl...

211 lines
7.9 KiB
Swift

//
// EditListAccountsViewController.swift
// Tusker
//
// Created by Shadowfacts on 12/17/19.
// Copyright © 2019 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
class EditListAccountsViewController: EnhancedTableViewController {
let mastodonController: MastodonController
let list: List
var dataSource: DataSource!
var nextRange: RequestRange?
var searchResultsController: EditListSearchResultsContainerViewController!
var searchController: UISearchController!
init(list: List, mastodonController: MastodonController) {
self.list = list
self.mastodonController = mastodonController
super.init(style: .plain)
title = String(format: NSLocalizedString("Edit %@", comment: "edit list screen title"), list.title)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemeneted")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "AccountTableViewCell", bundle: .main), forCellReuseIdentifier: "accountCell")
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 66
dataSource = DataSource(tableView: tableView, cellProvider: { (tableView, indexPath, item) -> UITableViewCell? in
guard case let .account(id) = item else { fatalError() }
let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountTableViewCell
cell.delegate = self
cell.updateUI(accountID: id)
return cell
})
dataSource.editListAccountsController = self
searchResultsController = EditListSearchResultsContainerViewController(mastodonController: mastodonController) { [unowned self] accountID in
Task {
await self.addAccount(id: accountID)
}
}
searchController = UISearchController(searchResultsController: searchResultsController)
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchResultsUpdater = searchResultsController
if #available(iOS 16.0, *) {
searchController.scopeBarActivation = .onSearchActivation
} else {
searchController.automaticallyShowsScopeBar = true
}
searchController.searchBar.autocapitalizationType = .none
searchController.searchBar.placeholder = NSLocalizedString("Search for accounts to add", comment: "edit list search field placeholder")
searchController.searchBar.delegate = searchResultsController
searchController.searchBar.scopeButtonTitles = ["Everyone", "People You Follow"]
definesPresentationContext = true
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Rename", comment: "rename list button title"), style: .plain, target: self, action: #selector(renameButtonPressed))
Task {
await loadAccounts()
}
}
func loadAccounts() async {
do {
let request = List.getAccounts(list)
let (accounts, pagination) = try await mastodonController.run(request)
self.nextRange = pagination?.older
await withCheckedContinuation { continuation in
mastodonController.persistentContainer.addAll(accounts: accounts) {
continuation.resume()
}
}
var snapshot = self.dataSource.snapshot()
if snapshot.indexOfSection(.accounts) == nil {
snapshot.appendSections([.accounts])
} else {
snapshot.deleteItems(snapshot.itemIdentifiers(inSection: .accounts))
}
snapshot.appendItems(accounts.map { .account(id: $0.id) })
await dataSource.apply(snapshot)
} catch {
let config = ToastConfiguration(from: error, with: "Error Loading Accounts", in: self) { [unowned self] toast in
toast.dismissToast(animated: true)
await self.loadAccounts()
}
self.showToast(configuration: config, animated: true)
}
}
private func addAccount(id: String) async {
do {
let req = List.add(list, accounts: [id])
_ = try await mastodonController.run(req)
self.searchController.isActive = false
await self.loadAccounts()
} catch {
let config = ToastConfiguration(from: error, with: "Error Adding Account", in: self) { [unowned self] toast in
toast.dismissToast(animated: true)
await self.addAccount(id: id)
}
self.showToast(configuration: config, animated: true)
}
}
private func removeAccount(id: String) async {
do {
let request = List.remove(list, accounts: [id])
_ = try await mastodonController.run(request)
await self.loadAccounts()
} catch {
let config = ToastConfiguration(from: error, with: "Error Removing Account", in: self) { [unowned self] toast in
toast.dismissToast(animated: true)
await self.removeAccount(id: id)
}
self.showToast(configuration: config, animated: true)
}
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
// MARK: - Interaction
@objc func renameButtonPressed() {
let alert = UIAlertController(title: NSLocalizedString("Rename List", comment: "rename list alert title"), message: nil, preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = self.list.title
}
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "rename list alert cancel button"), style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: NSLocalizedString("Rename", comment: "renaem list alert rename button"), style: .default, handler: { (_) in
guard let text = alert.textFields?.first?.text else {
fatalError()
}
let request = List.update(self.list, title: text)
self.mastodonController.run(request) { (response) in
guard case .success(_, _) = response else {
fatalError()
}
// todo: show success message somehow
}
}))
present(alert, animated: true)
}
}
extension EditListAccountsViewController {
enum Section: Hashable {
case accounts
}
enum Item: Hashable {
case account(id: String)
}
class DataSource: UITableViewDiffableDataSource<Section, Item> {
weak var editListAccountsController: EditListAccountsViewController?
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == .delete,
case let .account(id) = itemIdentifier(for: indexPath) else {
return
}
Task {
await self.editListAccountsController?.removeAccount(id: id)
}
}
}
}
extension EditListAccountsViewController: TuskerNavigationDelegate {
var apiController: MastodonController! { mastodonController }
}
extension EditListAccountsViewController: ToastableViewController {
}
extension EditListAccountsViewController: MenuActionProvider {
}