forked from shadowfacts/Tusker
344 lines
14 KiB
Swift
344 lines
14 KiB
Swift
//
|
|
// BaseStatusTableViewCell.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 11/19/19.
|
|
// Copyright © 2019 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import UIKit
|
|
import Pachyderm
|
|
import Combine
|
|
|
|
protocol StatusTableViewCellDelegate: TuskerNavigationDelegate {
|
|
func statusCellCollapsedStateChanged(_ cell: BaseStatusTableViewCell)
|
|
}
|
|
|
|
class BaseStatusTableViewCell: UITableViewCell {
|
|
var delegate: StatusTableViewCellDelegate? {
|
|
didSet {
|
|
contentLabel.navigationDelegate = delegate
|
|
}
|
|
}
|
|
|
|
@IBOutlet weak var avatarImageView: UIImageView!
|
|
@IBOutlet weak var displayNameLabel: UILabel!
|
|
@IBOutlet weak var usernameLabel: UILabel!
|
|
@IBOutlet weak var contentWarningLabel: UILabel!
|
|
@IBOutlet weak var collapseButton: UIButton!
|
|
@IBOutlet weak var contentLabel: StatusContentLabel!
|
|
@IBOutlet weak var attachmentsView: AttachmentsContainerView!
|
|
@IBOutlet weak var replyButton: UIButton!
|
|
@IBOutlet weak var favoriteButton: UIButton!
|
|
@IBOutlet weak var reblogButton: UIButton!
|
|
@IBOutlet weak var moreButton: UIButton!
|
|
|
|
var statusID: String!
|
|
var accountID: String!
|
|
|
|
var favorited = false {
|
|
didSet {
|
|
favoriteButton.tintColor = favorited ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor
|
|
}
|
|
}
|
|
var reblogged = false {
|
|
didSet {
|
|
reblogButton.tintColor = reblogged ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor
|
|
}
|
|
}
|
|
|
|
var statusState: StatusState!
|
|
var collapsible = false {
|
|
didSet {
|
|
collapseButton.isHidden = !collapsible
|
|
statusState?.collapsible = collapsible
|
|
}
|
|
}
|
|
var collapsed = false {
|
|
didSet {
|
|
statusState?.collapsed = collapsed
|
|
}
|
|
}
|
|
var showStatusAutomatically = false
|
|
|
|
var avatarURL: URL?
|
|
var attachmentDataTasks: [URLSessionDataTask] = []
|
|
|
|
private var statusUpdater: Cancellable?
|
|
private var accountUpdater: Cancellable?
|
|
|
|
deinit {
|
|
statusUpdater?.cancel()
|
|
accountUpdater?.cancel()
|
|
}
|
|
|
|
override func awakeFromNib() {
|
|
super.awakeFromNib()
|
|
|
|
displayNameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
|
|
usernameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
|
|
avatarImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
|
|
|
|
avatarImageView.layer.masksToBounds = true
|
|
|
|
attachmentsView.delegate = self
|
|
attachmentsView.layer.cornerRadius = 5
|
|
attachmentsView.layer.masksToBounds = true
|
|
|
|
collapseButton.layer.masksToBounds = true
|
|
collapseButton.layer.cornerRadius = 5
|
|
|
|
accessibilityElements = [displayNameLabel!, contentWarningLabel!, collapseButton!, contentLabel!, attachmentsView!]
|
|
attachmentsView.isAccessibilityElement = true
|
|
|
|
NotificationCenter.default.addObserver(self, selector: #selector(updateUIForPreferences), name: .preferencesChanged, object: nil)
|
|
|
|
statusUpdater = MastodonCache.statusSubject
|
|
.filter { $0.id == self.statusID }
|
|
.receive(on: DispatchQueue.main)
|
|
.sink(receiveValue: updateStatusState(status:))
|
|
|
|
accountUpdater = MastodonCache.accountSubject
|
|
.filter { $0.id == self.accountID }
|
|
.receive(on: DispatchQueue.main)
|
|
.sink(receiveValue: updateUI(account:))
|
|
}
|
|
|
|
func updateUI(statusID: String, state: StatusState) {
|
|
guard let status = MastodonCache.status(for: statusID) else {
|
|
fatalError("Missing cached status")
|
|
}
|
|
self.statusID = statusID
|
|
self.statusState = state
|
|
|
|
let account = status.account
|
|
self.accountID = account.id
|
|
updateUI(account: account)
|
|
|
|
updateUIForPreferences()
|
|
|
|
attachmentsView.updateUI(status: status)
|
|
attachmentsView.isAccessibilityElement = status.attachments.count > 0
|
|
attachmentsView.accessibilityLabel = String(format: NSLocalizedString("%d attachments", comment: "status attachments count accessibility label"), status.attachments.count)
|
|
|
|
updateStatusState(status: status)
|
|
|
|
contentLabel.statusID = statusID
|
|
|
|
contentWarningLabel.text = status.spoilerText
|
|
contentWarningLabel.isHidden = status.spoilerText.isEmpty
|
|
|
|
if state.unknown {
|
|
collapsible = !status.spoilerText.isEmpty
|
|
var shouldCollapse = collapsible
|
|
if !shouldCollapse,
|
|
let text = contentLabel.text,
|
|
text.count > 500 {
|
|
collapsible = true
|
|
shouldCollapse = true
|
|
}
|
|
if collapsible && showStatusAutomatically {
|
|
shouldCollapse = false
|
|
}
|
|
setCollapsed(shouldCollapse, animated: false)
|
|
|
|
state.collapsible = collapsible
|
|
state.collapsed = shouldCollapse
|
|
} else {
|
|
collapsible = state.collapsible!
|
|
setCollapsed(state.collapsed!, animated: false)
|
|
}
|
|
}
|
|
|
|
func updateStatusState(status: Status) {
|
|
favorited = status.favourited ?? false
|
|
reblogged = status.reblogged ?? false
|
|
|
|
if favorited {
|
|
favoriteButton.accessibilityLabel = NSLocalizedString("Undo Favorite", comment: "undo favorite button accessibility label")
|
|
} else {
|
|
favoriteButton.accessibilityLabel = NSLocalizedString("Favorite", comment: "favorite button accessibility label")
|
|
}
|
|
if reblogged {
|
|
reblogButton.accessibilityLabel = NSLocalizedString("Undo Reblog", comment: "undo reblog button accessibility label")
|
|
} else {
|
|
reblogButton.accessibilityLabel = NSLocalizedString("Reblog", comment: "reblog button accessibility label")
|
|
}
|
|
}
|
|
|
|
func updateUI(account: Account) {
|
|
usernameLabel.text = "@\(account.acct)"
|
|
avatarImageView.image = nil
|
|
avatarURL = account.avatar
|
|
ImageCache.avatars.get(account.avatar) { (data) in
|
|
guard let data = data, self.avatarURL == account.avatar else { return }
|
|
DispatchQueue.main.async {
|
|
self.avatarImageView.image = UIImage(data: data)
|
|
self.avatarURL = nil
|
|
}
|
|
}
|
|
}
|
|
|
|
@objc func updateUIForPreferences() {
|
|
guard let account = MastodonCache.account(for: accountID) else { return }
|
|
avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarImageView)
|
|
displayNameLabel.text = account.realDisplayName
|
|
}
|
|
|
|
override func prepareForReuse() {
|
|
super.prepareForReuse()
|
|
|
|
if let avatarURL = avatarURL {
|
|
ImageCache.avatars.cancel(avatarURL)
|
|
}
|
|
attachmentsView.attachmentViews.allObjects.forEach { $0.removeFromSuperview() }
|
|
showStatusAutomatically = false
|
|
}
|
|
|
|
@IBAction func collapseButtonPressed() {
|
|
setCollapsed(!collapsed, animated: true)
|
|
delegate?.statusCellCollapsedStateChanged(self)
|
|
}
|
|
|
|
func setCollapsed(_ collapsed: Bool, animated: Bool) {
|
|
self.collapsed = collapsed
|
|
|
|
contentLabel.isHidden = collapsed
|
|
attachmentsView.isHidden = attachmentsView.attachments.count == 0 || collapsed
|
|
|
|
let buttonImage = UIImage(systemName: collapsed ? "chevron.down" : "chevron.up")!
|
|
|
|
if animated, let buttonImageView = collapseButton.imageView {
|
|
// we need to use a keyframe animation for this, because we want to control the direction the chevron rotates
|
|
// when rotating ±π, UIKit will always rotate in the same direction
|
|
// using a keyframe to set an intermediate point in the animation allows us to force a specific direction
|
|
UIView.animateKeyframes(withDuration: 0.2, delay: 0, options: .calculationModeLinear, animations: {
|
|
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5) {
|
|
buttonImageView.transform = CGAffineTransform(rotationAngle: collapsed ? .pi / 2 : -.pi / 2)
|
|
}
|
|
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) {
|
|
buttonImageView.transform = CGAffineTransform(rotationAngle: .pi)
|
|
}
|
|
}, completion: { (finished) in
|
|
buttonImageView.transform = .identity
|
|
self.collapseButton.setImage(buttonImage, for: .normal)
|
|
})
|
|
} else {
|
|
collapseButton.setImage(buttonImage, for: .normal)
|
|
}
|
|
|
|
if collapsed {
|
|
collapseButton.accessibilityLabel = NSLocalizedString("Expand Status", comment: "expand status button accessibility label")
|
|
} else {
|
|
collapseButton.accessibilityLabel = NSLocalizedString("Collapse Status", comment: "collapse status button accessibility label")
|
|
}
|
|
|
|
}
|
|
|
|
@IBAction func replyPressed() {
|
|
delegate?.reply(to: statusID)
|
|
}
|
|
|
|
@IBAction func favoritePressed() {
|
|
guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
|
|
|
|
let oldValue = favorited
|
|
favorited = !favorited
|
|
|
|
let realStatus: Status = status.reblog ?? status
|
|
let request = (favorited ? Status.favourite : Status.unfavourite)(realStatus)
|
|
MastodonController.client.run(request) { response in
|
|
DispatchQueue.main.async {
|
|
if case let .success(newStatus, _) = response {
|
|
self.favorited = newStatus.favourited ?? false
|
|
MastodonCache.add(status: newStatus)
|
|
UIImpactFeedbackGenerator(style: .light).impactOccurred()
|
|
} else {
|
|
self.favorited = oldValue
|
|
print("Couldn't favorite status \(realStatus.id)")
|
|
// todo: display error message
|
|
UINotificationFeedbackGenerator().notificationOccurred(.error)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@IBAction func reblogPressed() {
|
|
guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
|
|
|
|
let oldValue = reblogged
|
|
reblogged = !reblogged
|
|
|
|
let realStatus: Status = status.reblog ?? status
|
|
let request = (reblogged ? Status.reblog : Status.unreblog)(realStatus)
|
|
MastodonController.client.run(request) { response in
|
|
DispatchQueue.main.async {
|
|
if case let .success(newStatus, _) = response {
|
|
self.reblogged = newStatus.reblogged ?? false
|
|
MastodonCache.add(status: newStatus)
|
|
UIImpactFeedbackGenerator(style: .light).impactOccurred()
|
|
} else {
|
|
self.reblogged = oldValue
|
|
print("Couldn't reblog status \(realStatus.id)")
|
|
// todo: display error message
|
|
UINotificationFeedbackGenerator().notificationOccurred(.error)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
@IBAction func morePressed() {
|
|
delegate?.showMoreOptions(forStatus: statusID)
|
|
}
|
|
|
|
@objc func accountPressed() {
|
|
delegate?.selected(account: accountID)
|
|
}
|
|
|
|
func getStatusCellPreviewProviders(for location: CGPoint, sourceViewController: UIViewController) -> PreviewProviders? {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
extension BaseStatusTableViewCell: AttachmentViewDelegate {
|
|
func showAttachmentsGallery(startingAt index: Int) {
|
|
guard let status = MastodonCache.status(for: statusID) else { fatalError("Missing cached status \(statusID!)") }
|
|
let sourceViews = status.attachments.map(attachmentsView.getAttachmentView(for:))
|
|
delegate?.showGallery(attachments: status.attachments, sourceViews: sourceViews, startIndex: index)
|
|
}
|
|
}
|
|
|
|
extension BaseStatusTableViewCell: MenuPreviewProvider {
|
|
var navigationDelegate: TuskerNavigationDelegate? { return delegate }
|
|
|
|
func getPreviewProviders(for location: CGPoint, sourceViewController: UIViewController) -> PreviewProviders? {
|
|
if avatarImageView.frame.contains(location) {
|
|
return (content: { ProfileTableViewController(accountID: self.accountID)}, actions: { self.actionsForProfile(accountID: self.accountID) })
|
|
} else if attachmentsView.frame.contains(location) {
|
|
let attachmentsViewLocation = attachmentsView.convert(location, from: self)
|
|
if let attachmentView = attachmentsView.attachmentViews.allObjects.first(where: { $0.frame.contains(attachmentsViewLocation) }),
|
|
let image = attachmentView.image {
|
|
let description = attachmentView.attachment.description
|
|
return (content: { self.delegate?.largeImage(image, description: description, sourceView: attachmentView) }, actions: { [] })
|
|
}
|
|
} else if contentLabel.frame.contains(location),
|
|
let link = contentLabel.getLink(atPoint: contentLabel.convert(location, from: self)) {
|
|
return (
|
|
content: { self.contentLabel.getViewController(forLink: link.url, inRange: link.range) },
|
|
actions: {
|
|
let text = (self.contentLabel.text! as NSString).substring(with: link.range)
|
|
if let mention = self.contentLabel.getMention(for: link.url, text: text) {
|
|
return self.actionsForProfile(accountID: mention.id)
|
|
} else if let hashtag = self.contentLabel.getHashtag(for: link.url, text: text) {
|
|
return self.actionsForHashtag(hashtag)
|
|
} else {
|
|
return self.actionsForURL(link.url)
|
|
}
|
|
}
|
|
)
|
|
}
|
|
return self.getStatusCellPreviewProviders(for: location, sourceViewController: sourceViewController)
|
|
}
|
|
}
|