A WIP iOS app for Mastodon and Pleroma.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

387 lines
15 KiB

//
// StatusTableViewCell.swift
// Tusker
//
// Created by Shadowfacts on 8/16/18.
// Copyright © 2018 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
protocol StatusTableViewCellDelegate {
func selected(account: Account)
func selected(mention: Mention)
func selected(tag: Hashtag)
func selected(url: URL)
func selected(status statusID: String)
func reply(to statusID: String)
func showLargeImage(_ image: UIImage, description: String?, animatingFrom originView: UIView)
func showMoreOptions(status statusID: String)
}
class StatusTableViewCell: UITableViewCell, PreferencesAdaptive {
var delegate: StatusTableViewCellDelegate?
@IBOutlet weak var displayNameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var contentLabel: StatusContentLabel!
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var reblogLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var attachmentsView: UIView!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var reblogButton: UIButton!
var statusID: String!
var account: Account!
var reblogger: Account?
var favorited: Bool = false {
didSet {
favoriteButton.tintColor = favorited ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor
}
}
var reblogged: Bool = false {
didSet {
reblogButton.tintColor = reblogged ? UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1) : tintColor
}
}
var avatarURL: URL?
var updateTimestampWorkItem: DispatchWorkItem?
var attachmentDataTasks: [URLSessionDataTask] = []
override func awakeFromNib() {
displayNameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
displayNameLabel.isUserInteractionEnabled = true
usernameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
usernameLabel.isUserInteractionEnabled = true
reblogLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(reblogLabelPressed)))
reblogLabel.isUserInteractionEnabled = true
avatarImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
avatarImageView.isUserInteractionEnabled = true
avatarImageView.layer.masksToBounds = true
attachmentsView.layer.cornerRadius = 5
attachmentsView.layer.masksToBounds = true
contentLabel.delegate = self
}
func updateUIForPreferences() {
avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarImageView)
if let reblogger = reblogger {
reblogLabel.text = "Reblogged by \(reblogger.realDisplayName)"
}
displayNameLabel.text = account.realDisplayName
}
func updateUI(for statusID: String) {
self.statusID = statusID
guard let status = StatusCache.get(id: statusID) else { fatalError("Missing cached status \(statusID)") }
let account: Account
if let reblog = status.reblog {
account = reblog.account
reblogger = status.account
reblogLabel.isHidden = false
} else {
account = status.account
reblogLabel.isHidden = true
reblogger = nil
}
self.account = account
updateUIForPreferences()
usernameLabel.text = "@\(account.acct)"
avatarImageView.image = nil
avatarURL = account.avatar
AvatarCache.shared.get(account.avatar) { image in
DispatchQueue.main.async {
self.avatarImageView.image = image
self.avatarURL = nil
}
}
updateTimestamp()
let attachments = status.attachments.filter({ $0.kind == .image })
if attachments.count > 0 {
attachmentsView.isHidden = false
let width = attachmentsView.bounds.width
let height: CGFloat = 200
switch attachments.count {
case 1:
addAttachmentView(frame: CGRect(x: 0, y: 0, width: width, height: height), attachment: attachments[0])
case 2:
addAttachmentView(frame: CGRect(x: 0, y: 0, width: width / 2 - 4, height: height), attachment: attachments[0])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: 0, width: width / 2 - 4, height: height), attachment: attachments[1])
case 3:
addAttachmentView(frame: CGRect(x: 0, y: 0, width: width / 2 - 4, height: height), attachment: attachments[0])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: 0, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[1])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: height / 2 + 4, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[2])
case 4:
addAttachmentView(frame: CGRect(x: 0, y: 0, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[0])
addAttachmentView(frame: CGRect(x: 0, y: height / 2 + 4, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[1])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: 0, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[2])
addAttachmentView(frame: CGRect(x: width / 2 + 4, y: height / 2 + 4, width: width / 2 - 4, height: height / 2 - 4), attachment: attachments[3])
default:
fatalError("Too many attachments")
}
} else {
attachmentsView.isHidden = true
}
let realStatus = status.reblog ?? status
favorited = realStatus.favourited ?? false
reblogged = realStatus.reblogged ?? false
contentLabel.statusID = statusID
}
func updateTimestamp() {
guard let status = StatusCache.get(id: statusID) else { fatalError("Missing cached status \(statusID!)") }
timestampLabel.text = status.createdAt.timeAgoString()
let delay: DispatchTimeInterval?
switch status.createdAt.timeAgo().1 {
case .second:
delay = .seconds(10)
case .minute:
delay = .seconds(60)
default:
delay = nil
}
if let delay = delay {
updateTimestampWorkItem = DispatchWorkItem {
self.updateTimestamp()
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: updateTimestampWorkItem!)
} else {
updateTimestampWorkItem = nil
}
}
func addAttachmentView(frame: CGRect, attachment: Attachment) {
let attachmentView = AttachmentView(frame: frame, attachment: attachment)
attachmentView.delegate = self
attachmentsView.addSubview(attachmentView)
}
override func prepareForReuse() {
if let url = avatarURL {
AvatarCache.shared.cancel(url)
}
updateTimestampWorkItem?.cancel()
updateTimestampWorkItem = nil
attachmentsView.subviews.forEach { view in
(view as? AttachmentView)?.task?.cancel()
view.removeFromSuperview()
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
delegate?.selected(status: statusID)
}
}
@IBAction func replyPressed(_ sender: Any) {
delegate?.reply(to: statusID)
}
@objc func accountPressed() {
delegate?.selected(account: account)
}
@objc func reblogLabelPressed() {
guard let reblogger = reblogger else { return }
delegate?.selected(account: reblogger)
}
@IBAction func favoritePressed(_ sender: Any) {
guard let status = StatusCache.get(id: 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.shared.client.run(request) { response in
DispatchQueue.main.async {
self.favorited = realStatus.favourited ?? false
if case .success = response {
self.favorited = realStatus.favourited ?? false
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(_ sender: Any) {
guard let status = StatusCache.get(id: 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.shared.client.run(request) { response in
self.reblogged = realStatus.reblogged ?? false
DispatchQueue.main.async {
if case .success = response {
self.reblogged = realStatus.reblogged ?? false
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(_ sender: Any) {
delegate?.showMoreOptions(status: statusID)
}
}
extension StatusTableViewCell: TableViewSwipeActionProvider {
static var favoriteActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 137/131, height: 30)).image { _ in
UIImage(named: "Favorite")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 137/131, height: 30))
}
static var reblogActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 927/558, height: 30)).image { _ in
UIImage(named: "Reblog")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 927/558, height: 30))
}
static var replyActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 205/151, height: 30)).image { _ in
UIImage(named: "Reply")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 205/151, height: 30))
}
static var moreActionImage: UIImage = UIGraphicsImageRenderer(size: CGSize(width: 30 * 2/1, height: 30)).image { _ in
UIImage(named: "More")!.draw(in: CGRect(x: 0, y: 0, width: 30 * 2/1, height: 30))
}
func leadingSwipeActionsConfiguration() -> UISwipeActionsConfiguration? {
guard let status = StatusCache.get(id: statusID) else { fatalError("Missing cached status \(statusID!)") }
let favoriteTitle: String
let favoriteRequest: Request<Status>
let favoriteColor: UIColor
if status.favourited ?? false {
favoriteTitle = "Unfavorite"
favoriteRequest = Status.unfavourite(status)
favoriteColor = UIColor(displayP3Red: 235/255, green: 77/255, blue: 62/255, alpha: 1)
} else {
favoriteTitle = "Favorite"
favoriteRequest = Status.favourite(status)
favoriteColor = UIColor(displayP3Red: 1, green: 204/255, blue: 0, alpha: 1)
}
let favorite = UIContextualAction(style: .normal, title: favoriteTitle) { (action, view, completion) in
MastodonController.shared.client.run(favoriteRequest, completion: { response in
DispatchQueue.main.async {
guard case let .success(status, _) = response else {
completion(false)
return
}
completion(true)
StatusCache.add(status)
self.updateUI(for: self.statusID)
}
})
}
favorite.image = StatusTableViewCell.favoriteActionImage
favorite.backgroundColor = favoriteColor
let reblogTitle: String
let reblogRequest: Request<Status>
let reblogColor: UIColor
if status.reblogged ?? false {
reblogTitle = "Unreblog"
reblogRequest = Status.unreblog(status)
reblogColor = UIColor(displayP3Red: 235/255, green: 77/255, blue: 62/255, alpha: 1)
} else {
reblogTitle = "Reblog"
reblogRequest = Status.reblog(status)
reblogColor = tintColor
}
let reblog = UIContextualAction(style: .normal, title: reblogTitle) { (action, view, completion) in
MastodonController.shared.client.run(reblogRequest, completion: { response in
DispatchQueue.main.async {
guard case let .success(status, _) = response else {
completion(false)
return
}
completion(true)
StatusCache.add(status)
self.updateUI(for: self.statusID)
}
})
}
reblog.image = StatusTableViewCell.reblogActionImage
reblog.backgroundColor = reblogColor
return UISwipeActionsConfiguration(actions: [favorite, reblog])
}
func trailingSwipeActionsConfiguration() -> UISwipeActionsConfiguration? {
let reply = UIContextualAction(style: .normal, title: "Reply") { (action, view, completion) in
completion(true)
self.delegate?.reply(to: self.statusID)
}
reply.image = StatusTableViewCell.replyActionImage
reply.backgroundColor = tintColor
let more = UIContextualAction(style: .normal, title: "More") { (action, view, completion) in
completion(true)
self.delegate?.showMoreOptions(status: self.statusID)
}
more.image = StatusTableViewCell.moreActionImage
more.backgroundColor = .gray
return UISwipeActionsConfiguration(actions: [reply, more])
}
}
extension StatusTableViewCell: HTMLContentLabelDelegate {
func selected(mention: Mention) {
delegate?.selected(mention: mention)
}
func selected(tag: Hashtag) {
delegate?.selected(tag: tag)
}
func selected(url: URL) {
delegate?.selected(url: url)
}
}
extension StatusTableViewCell: AttachmentViewDelegate {
func showLargeAttachment(for attachmentView: AttachmentView) {
delegate?.showLargeImage(attachmentView.image!, description: attachmentView.attachment.description, animatingFrom: attachmentView)
}
}