Tusker/Tusker/Views/Status/TimelineStatusCollectionVie...

500 lines
22 KiB
Swift

//
// TimelineStatusCollectionViewCell.swift
// Tusker
//
// Created by Shadowfacts on 10/1/22.
// Copyright © 2022 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
@MainActor
protocol TimelineStatusCollectionViewCellDelegate: AnyObject, TuskerNavigationDelegate, MenuActionProvider {
func statusCellCollapsedStateChanged(_ cell: TimelineStatusCollectionViewCell)
}
class TimelineStatusCollectionViewCell: UICollectionViewListCell {
// MARK: Subviews
private let reblogLabel = EmojiLabel().configure {
$0.textColor = .secondaryLabel
// this needs to have a higher priorty than the content container's zero height constraint
$0.setContentHuggingPriority(.defaultHigh, for: .vertical)
// TODO: tap gesture
// $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(reblogLabelPressed)))
}
private lazy var mainContainer = UIView().configure {
avatarImageView.translatesAutoresizingMaskIntoConstraints = false
$0.addSubview(avatarImageView)
contentVStack.translatesAutoresizingMaskIntoConstraints = false
$0.addSubview(contentVStack)
metaIndicatorsView.translatesAutoresizingMaskIntoConstraints = false
$0.addSubview(metaIndicatorsView)
NSLayoutConstraint.activate([
avatarImageView.leadingAnchor.constraint(equalTo: $0.leadingAnchor),
avatarImageView.topAnchor.constraint(equalTo: $0.topAnchor),
contentVStack.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 8),
contentVStack.trailingAnchor.constraint(equalTo: $0.trailingAnchor),
contentVStack.topAnchor.constraint(equalTo: $0.topAnchor),
contentVStack.bottomAnchor.constraint(equalTo: $0.bottomAnchor),
metaIndicatorsView.leadingAnchor.constraint(greaterThanOrEqualTo: $0.leadingAnchor),
metaIndicatorsView.trailingAnchor.constraint(equalTo: avatarImageView.trailingAnchor),
metaIndicatorsView.topAnchor.constraint(equalTo: avatarImageView.bottomAnchor, constant: 4),
])
}
private static let avatarImageViewSize: CGFloat = 50
private let avatarImageView = CachedImageView(cache: .avatars).configure {
$0.layer.masksToBounds = true
NSLayoutConstraint.activate([
$0.heightAnchor.constraint(equalToConstant: TimelineStatusCollectionViewCell.avatarImageViewSize),
$0.widthAnchor.constraint(equalToConstant: TimelineStatusCollectionViewCell.avatarImageViewSize),
])
// TODO: context menu
// $0.addInteraction(UIContextMenuInteraction(delegate: self))
// TODO: drag gesture
// $0.addInteraction(UIDragInteraction(delegate: self))
// TODO: tap gesture
// $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
}
private let metaIndicatorsView = StatusMetaIndicatorsView()
private lazy var contentVStack = UIStackView(arrangedSubviews: [
nameHStack,
contentWarningLabel,
collapseButton,
contentContainer,
]).configure {
$0.axis = .vertical
$0.spacing = 4
$0.alignment = .fill
}
private lazy var nameHStack = UIStackView(arrangedSubviews: [
displayNameLabel,
usernameLabel,
pinImageView,
timestampLabel,
]).configure {
$0.axis = .horizontal
$0.spacing = 4
// TODO: tap gesture
// $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
}
private let displayNameLabel = EmojiLabel().configure {
$0.font = UIFont(descriptor: .preferredFontDescriptor(withTextStyle: .body).addingAttributes([
.traits: [
UIFontDescriptor.TraitKey.weight: UIFont.Weight.semibold.rawValue,
]
]), size: 0)
$0.setContentHuggingPriority(.init(251), for: .horizontal)
$0.setContentCompressionResistancePriority(.init(749), for: .horizontal)
}
private let usernameLabel = UILabel().configure {
$0.textColor = .secondaryLabel
$0.font = UIFont(descriptor: .preferredFontDescriptor(withTextStyle: .body).addingAttributes([
.traits: [
UIFontDescriptor.TraitKey.weight: UIFont.Weight.light.rawValue,
]
]), size: 0)
$0.setContentHuggingPriority(.init(249), for: .horizontal)
$0.setContentCompressionResistancePriority(.init(748), for: .horizontal)
}
private let pinImageView = UIImageView(image: UIImage(systemName: "pin.fill")).configure {
$0.tintColor = .secondaryLabel
$0.setContentHuggingPriority(.init(251), for: .horizontal)
}
private let timestampLabel = UILabel().configure {
$0.textColor = .secondaryLabel
$0.font = UIFont(descriptor: .preferredFontDescriptor(withTextStyle: .body).addingAttributes([
.traits: [
UIFontDescriptor.TraitKey.weight: UIFont.Weight.light.rawValue,
]
]), size: 0)
}
private lazy var contentWarningLabel = EmojiLabel().configure {
$0.textColor = .secondaryLabel
$0.font = UIFont(descriptor: .preferredFontDescriptor(withTextStyle: .body).addingAttributes([
.traits: [
UIFontDescriptor.TraitKey.weight: UIFont.Weight.bold.rawValue,
]
]), size: 0)
// this needs to have a higher priorty than the content container's zero height constraint
$0.setContentHuggingPriority(.defaultHigh, for: .vertical)
$0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(collapseButtonPressed)))
}
private lazy var collapseButton = UIButton(configuration: {
var config = UIButton.Configuration.filled()
config.image = UIImage(systemName: "chevron.down")
return config
}()).configure {
$0.setContentHuggingPriority(.defaultHigh, for: .vertical)
$0.addTarget(self, action: #selector(collapseButtonPressed), for: .touchUpInside)
}
private let contentContainer = StatusContentContainer().configure {
$0.setContentHuggingPriority(.defaultLow, for: .vertical)
}
private var contentTextView: StatusContentTextView {
contentContainer.contentTextView
}
private var cardView: StatusCardView {
contentContainer.cardView
}
private var attachmentsView: AttachmentsContainerView {
contentContainer.attachmentsView
}
private var pollView: StatusPollView {
contentContainer.pollView
}
private var placeholderReplyButtonLeadingConstraint: NSLayoutConstraint!
private lazy var actionsContainer = UIView().configure {
replyButton.translatesAutoresizingMaskIntoConstraints = false
$0.addSubview(replyButton)
favoriteButton.translatesAutoresizingMaskIntoConstraints = false
$0.addSubview(favoriteButton)
reblogButton.translatesAutoresizingMaskIntoConstraints = false
$0.addSubview(reblogButton)
moreButton.translatesAutoresizingMaskIntoConstraints = false
$0.addSubview(moreButton)
placeholderReplyButtonLeadingConstraint = replyButton.leadingAnchor.constraint(equalTo: $0.leadingAnchor)
NSLayoutConstraint.activate([
favoriteButton.widthAnchor.constraint(equalTo: replyButton.widthAnchor),
reblogButton.widthAnchor.constraint(equalTo: replyButton.widthAnchor),
moreButton.widthAnchor.constraint(equalTo: replyButton.widthAnchor),
// TODO: gah
placeholderReplyButtonLeadingConstraint,
replyButton.topAnchor.constraint(equalTo: $0.topAnchor),
replyButton.bottomAnchor.constraint(equalTo: $0.bottomAnchor),
favoriteButton.leadingAnchor.constraint(equalTo: replyButton.trailingAnchor),
favoriteButton.topAnchor.constraint(equalTo: $0.topAnchor),
favoriteButton.bottomAnchor.constraint(equalTo: $0.bottomAnchor),
reblogButton.leadingAnchor.constraint(equalTo: favoriteButton.trailingAnchor),
reblogButton.topAnchor.constraint(equalTo: $0.topAnchor),
reblogButton.bottomAnchor.constraint(equalTo: $0.bottomAnchor),
moreButton.leadingAnchor.constraint(equalTo: reblogButton.trailingAnchor),
moreButton.trailingAnchor.constraint(equalTo: $0.trailingAnchor),
moreButton.topAnchor.constraint(equalTo: $0.topAnchor),
moreButton.bottomAnchor.constraint(equalTo: $0.bottomAnchor),
])
}
private let replyButton = UIButton().configure {
$0.setImage(UIImage(systemName: "arrowshape.turn.up.left.fill"), for: .normal)
}
private let favoriteButton = UIButton().configure {
$0.setImage(UIImage(systemName: "star.fill"), for: .normal)
}
private let reblogButton = UIButton().configure {
$0.setImage(UIImage(systemName: "repeat"), for: .normal)
}
private let moreButton = UIButton().configure {
$0.setImage(UIImage(systemName: "ellipsis"), for: .normal)
$0.showsMenuAsPrimaryAction = true
}
// MARK: Cell state
private var mainContainerTopToReblogLabelConstraint: NSLayoutConstraint!
private var mainContainerTopToSelfConstraint: NSLayoutConstraint!
private var mainContainerBottomToActionsConstraint: NSLayoutConstraint!
private var mainContainerBottomToSelfConstraint: NSLayoutConstraint!
weak var mastodonController: MastodonController!
weak var delegate: TimelineStatusCollectionViewCellDelegate?
var showStatusAutomatically: Bool {
// TODO: needed once conversation controller refactored
false
}
var showReplyIndicator: Bool {
// TODO: needed once conversation controller refactored
false
}
var showPinned: Bool {
// TODO: needed once profile controller refactored
false
}
private(set) var statusID: String!
private(set) var statusState = StatusState.unknown
private var accountID: String!
private var reblogStatusID: String?
private var rebloggerID: String?
private var firstLayout = true
private var isGrayscale = false
override init(frame: CGRect) {
super.init(frame: frame)
for subview in [reblogLabel, mainContainer, actionsContainer] {
subview.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(subview)
}
mainContainerTopToReblogLabelConstraint = mainContainer.topAnchor.constraint(equalTo: reblogLabel.bottomAnchor, constant: 4)
mainContainerTopToSelfConstraint = mainContainer.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8)
mainContainerBottomToActionsConstraint = mainContainer.bottomAnchor.constraint(equalTo: actionsContainer.topAnchor)
mainContainerBottomToSelfConstraint = mainContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -6)
let metaIndicatorsBottomConstraint = metaIndicatorsView.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -6)
// sometimes during intermediate layouts, there are conflicting constraints, so let this one get broken temporarily, to avoid a bunch of printing
metaIndicatorsBottomConstraint.priority = .init(999)
NSLayoutConstraint.activate([
// why is this 4 but the mainContainerTopSelfConstraint constant 8? because this looks more balanced
reblogLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
reblogLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
reblogLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
mainContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
mainContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
actionsContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
actionsContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
// yes, this is deliberately 6. 4 looks to cramped, 8 looks uneven
actionsContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -6),
metaIndicatorsBottomConstraint,
])
updateActionsVisibility()
NotificationCenter.default.addObserver(self, selector: #selector(preferencesChanged), name: .preferencesChanged, object: nil)
// TEMP
reblogLabel.text = "Reblogged by Person"
avatarImageView.backgroundColor = .red
displayNameLabel.text = "Display name"
usernameLabel.text = "@username"
timestampLabel.text = "2m"
contentWarningLabel.text = "Content Warning"
contentTextView.setTextFromHtml("<p>Weeeeeeeee</p>")
attachmentsView.backgroundColor = .red
metaIndicatorsView.placeholder()
// contentWarningLabel.isHidden = true
// collapseButton.isHidden = true
// cardView.isHidden = true
// pollView.isHidden = true
// attachmentsView.isHidden = true
// actionsContainer.isHidden = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
if firstLayout {
firstLayout = false
// the button's image view doesn't exist until after the first layout
// accessing it before that cause the button to layoutIfNeeded which generates a broken, intermediate layout and prints a bunch of unhelpful autolayout warnings
// so we wait until after the first layout pass to setup the reply button's real constraint
placeholderReplyButtonLeadingConstraint.isActive = false
replyButton.imageView!.leadingAnchor.constraint(equalTo: contentTextView.leadingAnchor).isActive = true
}
}
func updateUI(statusID: String, state: StatusState) {
guard var status = mastodonController.persistentContainer.status(for: statusID) else {
fatalError()
}
self.statusState = state
if let rebloggedStatus = status.reblog {
reblogStatusID = statusID
rebloggerID = status.account.id
reblogLabel.isHidden = false
mainContainerTopToReblogLabelConstraint.isActive = true
mainContainerTopToSelfConstraint.isActive = false
updateRebloggerLabel(reblogger: status.account)
status = rebloggedStatus
} else {
reblogStatusID = nil
rebloggerID = nil
reblogLabel.isHidden = true
mainContainerTopToReblogLabelConstraint.isActive = false
mainContainerTopToSelfConstraint.isActive = true
}
doUpdateUI(status: status)
}
private func doUpdateUI(status: StatusMO) {
self.statusID = status.id
self.accountID = status.account.id
let account = status.account
usernameLabel.text = "@\(account.acct)"
contentTextView.setTextFrom(status: status)
updateGrayscaleableUI(account: account, status: status)
updateUIForPreferences(account: account, status: status)
cardView.card = status.card
cardView.isHidden = status.card == nil
cardView.navigationDelegate = delegate
cardView.actionProvider = delegate
attachmentsView.updateUI(status: status)
updateStatusState(status: status)
contentWarningLabel.text = status.spoilerText
contentWarningLabel.isHidden = status.spoilerText.isEmpty
if !contentWarningLabel.isHidden {
contentWarningLabel.setEmojis(status.emojis, identifier: statusID)
}
let reblogDisabled: Bool
if mastodonController.instanceFeatures.boostToOriginalAudience {
reblogDisabled = status.visibility == .direct || (status.visibility == .private && status.account.id != mastodonController.account.id)
} else {
reblogDisabled = status.visibility == .private || status.visibility == .direct
}
reblogButton.isEnabled = !reblogDisabled && mastodonController.loggedIn
favoriteButton.isEnabled = mastodonController.loggedIn
replyButton.isEnabled = mastodonController.loggedIn
if statusState.unknown {
statusState.resolveFor(status: status, text: contentTextView.text)
if statusState.collapsible! && showStatusAutomatically {
statusState.collapsed = false
}
}
contentContainer.setCollapsed(statusState.collapsed!)
contentContainer.alpha = statusState.collapsed! ? 0 : 1
collapseButton.imageView!.transform = CGAffineTransform(rotationAngle: statusState.collapsed! ? .pi : 0)
if statusState.collapsed! {
collapseButton.accessibilityLabel = NSLocalizedString("Expand Status", comment: "expand status button accessibility label")
} else {
collapseButton.accessibilityLabel = NSLocalizedString("Collapse Status", comment: "collapse status button accessibility label")
}
}
func updateUIForPreferences(account: AccountMO, status: StatusMO) {
avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadiusFraction * TimelineStatusCollectionViewCell.avatarImageViewSize
attachmentsView.contentHidden = Preferences.shared.blurAllMedia || status.sensitive
if showReplyIndicator {
metaIndicatorsView.allowedIndicators = .all
} else {
metaIndicatorsView.allowedIndicators = .all.subtracting(.reply)
}
if isGrayscale != Preferences.shared.grayscaleImages {
updateGrayscaleableUI(account: account, status: status)
}
if let rebloggerID,
let reblogger = mastodonController.persistentContainer.account(for: rebloggerID) {
updateRebloggerLabel(reblogger: reblogger)
}
}
private func updateRebloggerLabel(reblogger: AccountMO) {
if Preferences.shared.hideCustomEmojiInUsernames {
reblogLabel.text = "Reblogged by \(reblogger.displayNameWithoutCustomEmoji)"
reblogLabel.removeEmojis()
} else {
reblogLabel.text = "Reblogged by \(reblogger.displayOrUserName)"
reblogLabel.setEmojis(reblogger.emojis, identifier: reblogger.id)
}
}
func updateGrayscaleableUI(account: AccountMO, status: StatusMO) {
isGrayscale = Preferences.shared.grayscaleImages
avatarImageView.update(for: account.avatar)
if contentTextView.hasEmojis {
contentTextView.setTextFrom(status: status)
}
displayNameLabel.updateForAccountDisplayName(account: account)
}
func updateStatusState(status: StatusMO) {
if status.favourited {
favoriteButton.tintColor = UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1)
favoriteButton.accessibilityLabel = NSLocalizedString("Undo Favorite", comment: "undo favorite button accessibility label")
} else {
favoriteButton.tintColor = nil
favoriteButton.accessibilityLabel = NSLocalizedString("Favorite", comment: "favorite button accessibility label")
}
if status.reblogged {
reblogButton.tintColor = UIColor(displayP3Red: 1, green: 0.8, blue: 0, alpha: 1)
reblogButton.accessibilityLabel = NSLocalizedString("Undo Reblog", comment: "undo reblog button accessibility label")
} else {
reblogButton.tintColor = nil
reblogButton.accessibilityLabel = NSLocalizedString("Reblog", comment: "reblog button accessibility label")
}
// keep menu in sync with changed states e.g. bookmarked, muted
// do not include reply action here, because the cell already contains a button for it
moreButton.menu = UIMenu(title: "", image: nil, identifier: nil, options: [], children: delegate?.actionsForStatus(status, sourceView: moreButton, includeReply: false) ?? [])
pollView.isHidden = status.poll == nil
pollView.mastodonController = mastodonController
pollView.toastableViewController = delegate?.toastableViewController
pollView.updateUI(status: status, poll: status.poll)
}
private func updateActionsVisibility() {
if Preferences.shared.hideActionsInTimeline {
actionsContainer.isHidden = true
mainContainerBottomToSelfConstraint.isActive = true
mainContainerBottomToActionsConstraint.isActive = false
} else {
actionsContainer.isHidden = false
mainContainerBottomToSelfConstraint.isActive = false
mainContainerBottomToActionsConstraint.isActive = true
}
}
@objc private func preferencesChanged() {
guard let mastodonController,
let status = mastodonController.persistentContainer.status(for: statusID) else {
return
}
updateUIForPreferences(account: status.account, status: status)
// only needs to happen when prefs change, rather than in updateUIForPrefs b/c this is setup correctly during init
let oldState = actionsContainer.isHidden
if oldState != Preferences.shared.hideActionsInTimeline {
updateActionsVisibility()
delegate?.statusCellCollapsedStateChanged(self)
}
}
// MARK: Interaction
@objc func collapseButtonPressed() {
statusState.collapsed!.toggle()
// this delegate call causes the collection view to reconfigure this cell, at which point (and inside of the collection view's animation handling) we'll update the contentContainer
delegate?.statusCellCollapsedStateChanged(self)
}
}