From 780e8b09b7853d91a6969a05453586c47a9cf3b7 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Wed, 5 Oct 2022 17:40:00 -0400 Subject: [PATCH] Status cell UI --- Tusker.xcodeproj/project.pbxproj | 4 + .../Timeline/TimelineViewController.swift | 16 +- Tusker/Views/CachedImageView.swift | 63 ++++ .../Views/Status/StatusContentContainer.swift | 8 +- .../TimelineStatusCollectionViewCell.swift | 277 +++++++++++++++--- 5 files changed, 318 insertions(+), 50 deletions(-) create mode 100644 Tusker/Views/CachedImageView.swift diff --git a/Tusker.xcodeproj/project.pbxproj b/Tusker.xcodeproj/project.pbxproj index 091e73e9..eb269ad4 100644 --- a/Tusker.xcodeproj/project.pbxproj +++ b/Tusker.xcodeproj/project.pbxproj @@ -219,6 +219,7 @@ D6ADB6EA28E91C30009924AB /* TimelineStatusCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6ADB6E928E91C30009924AB /* TimelineStatusCollectionViewCell.swift */; }; D6ADB6EC28EA73CB009924AB /* StatusContentContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6ADB6EB28EA73CB009924AB /* StatusContentContainer.swift */; }; D6ADB6EE28EA74E8009924AB /* UIView+Configure.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6ADB6ED28EA74E8009924AB /* UIView+Configure.swift */; }; + D6ADB6F028ED1F25009924AB /* CachedImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6ADB6EF28ED1F25009924AB /* CachedImageView.swift */; }; D6AEBB3E2321638100E5038B /* UIActivity+Types.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6AEBB3D2321638100E5038B /* UIActivity+Types.swift */; }; D6AEBB412321642700E5038B /* SendMesasgeActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6AEBB402321642700E5038B /* SendMesasgeActivity.swift */; }; D6AEBB432321685E00E5038B /* OpenInSafariActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6AEBB422321685E00E5038B /* OpenInSafariActivity.swift */; }; @@ -568,6 +569,7 @@ D6ADB6E928E91C30009924AB /* TimelineStatusCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimelineStatusCollectionViewCell.swift; sourceTree = ""; }; D6ADB6EB28EA73CB009924AB /* StatusContentContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusContentContainer.swift; sourceTree = ""; }; D6ADB6ED28EA74E8009924AB /* UIView+Configure.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIView+Configure.swift"; sourceTree = ""; }; + D6ADB6EF28ED1F25009924AB /* CachedImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CachedImageView.swift; sourceTree = ""; }; D6AEBB3D2321638100E5038B /* UIActivity+Types.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIActivity+Types.swift"; sourceTree = ""; }; D6AEBB402321642700E5038B /* SendMesasgeActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SendMesasgeActivity.swift; sourceTree = ""; }; D6AEBB422321685E00E5038B /* OpenInSafariActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenInSafariActivity.swift; sourceTree = ""; }; @@ -1255,6 +1257,7 @@ children = ( D6B4A4FE2506B81A000C81C1 /* AccountDisplayNameLabel.swift */, D68E6F5E253C9B2D001A1B4C /* BaseEmojiLabel.swift */, + D6ADB6EF28ED1F25009924AB /* CachedImageView.swift */, D6895DC328D65342006341DA /* ConfirmReblogStatusPreviewView.swift */, D620483523D38075008A63EF /* ContentTextView.swift */, D6E426B225337C7000C02E1C /* CustomEmojiImageView.swift */, @@ -1756,6 +1759,7 @@ D6BC9DB3232D4C07002CA326 /* WellnessPrefsView.swift in Sources */, D64BC18F23C18B9D000D0238 /* FollowRequestNotificationTableViewCell.swift in Sources */, D62E9989279DB2D100C26176 /* InstanceFeatures.swift in Sources */, + D6ADB6F028ED1F25009924AB /* CachedImageView.swift in Sources */, D693DE5923FE24310061E07D /* InteractivePushTransition.swift in Sources */, D69693FA25859A8000F4E116 /* ComposeSceneDelegate.swift in Sources */, D6A3BC8A2321F79B00FD64D5 /* AccountTableViewCell.swift in Sources */, diff --git a/Tusker/Screens/Timeline/TimelineViewController.swift b/Tusker/Screens/Timeline/TimelineViewController.swift index 27c6f241..7fb04570 100644 --- a/Tusker/Screens/Timeline/TimelineViewController.swift +++ b/Tusker/Screens/Timeline/TimelineViewController.swift @@ -331,11 +331,19 @@ extension TimelineViewController: UICollectionViewDelegate { } } +extension TimelineViewController: TuskerNavigationDelegate { + var apiController: MastodonController { mastodonController } +} + +extension TimelineViewController: MenuActionProvider { +} + extension TimelineViewController: TimelineStatusCollectionViewCellDelegate { func statusCellCollapsedStateChanged(_ cell: TimelineStatusCollectionViewCell) { - let indexPath = collectionView.indexPath(for: cell)! - var snapshot = dataSource.snapshot() - snapshot.reconfigureItems([dataSource.itemIdentifier(for: indexPath)!]) - dataSource.apply(snapshot, animatingDifferences: true) + if let indexPath = collectionView.indexPath(for: cell) { + var snapshot = dataSource.snapshot() + snapshot.reconfigureItems([dataSource.itemIdentifier(for: indexPath)!]) + dataSource.apply(snapshot, animatingDifferences: true) + } } } diff --git a/Tusker/Views/CachedImageView.swift b/Tusker/Views/CachedImageView.swift new file mode 100644 index 00000000..8183a0e8 --- /dev/null +++ b/Tusker/Views/CachedImageView.swift @@ -0,0 +1,63 @@ +// +// CachedImageView.swift +// Tusker +// +// Created by Shadowfacts on 10/4/22. +// Copyright © 2022 Shadowfacts. All rights reserved. +// + +import UIKit + +class CachedImageView: UIImageView { + + private let cache: ImageCache + private var url: URL? + private var isGrayscale = false + private var fetchTask: Task? + + init(cache: ImageCache) { + self.cache = cache + + super.init(frame: .zero) + + NotificationCenter.default.addObserver(self, selector: #selector(preferencesChanged), name: .preferencesChanged, object: nil) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update(for url: URL?) { + if url != self.url { + self.url = url + updateImage() + } + } + + @objc private func preferencesChanged() { + if isGrayscale != Preferences.shared.grayscaleImages { + updateImage() + } + } + + private func updateImage() { + fetchTask?.cancel() + fetchTask = Task(priority: .high) { + self.image = nil + guard let url else { + return + } + let (_, image) = await cache.get(url) + guard let image else { + return + } + try Task.checkCancellation() + // TODO: check that this isn't on the main thread + guard let transformedImage = ImageGrayscalifier.convertIfNecessary(url: url, image: image) else { + return + } + self.image = transformedImage + } + } + +} diff --git a/Tusker/Views/Status/StatusContentContainer.swift b/Tusker/Views/Status/StatusContentContainer.swift index c6f47df2..ffbb7ff2 100644 --- a/Tusker/Views/Status/StatusContentContainer.swift +++ b/Tusker/Views/Status/StatusContentContainer.swift @@ -11,9 +11,11 @@ import UIKit class StatusContentContainer: UIView { let contentTextView = StatusContentTextView().configure { - $0.defaultFont = .systemFont(ofSize: 16) - $0.isScrollEnabled = false - $0.backgroundColor = nil + $0.defaultFont = .systemFont(ofSize: 16) + $0.isScrollEnabled = false + $0.backgroundColor = nil + $0.isEditable = false + $0.isSelectable = false } let cardView = StatusCardView().configure { diff --git a/Tusker/Views/Status/TimelineStatusCollectionViewCell.swift b/Tusker/Views/Status/TimelineStatusCollectionViewCell.swift index 6f7fbfe0..35244d66 100644 --- a/Tusker/Views/Status/TimelineStatusCollectionViewCell.swift +++ b/Tusker/Views/Status/TimelineStatusCollectionViewCell.swift @@ -10,23 +10,15 @@ import UIKit import Pachyderm @MainActor -protocol TimelineStatusCollectionViewCellDelegate: AnyObject { +protocol TimelineStatusCollectionViewCellDelegate: AnyObject, TuskerNavigationDelegate, MenuActionProvider { func statusCellCollapsedStateChanged(_ cell: TimelineStatusCollectionViewCell) } class TimelineStatusCollectionViewCell: UICollectionViewListCell { - private lazy var vStack = UIStackView(arrangedSubviews: [ - reblogLabel, - reblogSpacer, - mainContainer, - actionsContainer, - ]).configure { - $0.axis = .vertical - $0.alignment = .fill - } + // MARK: Subviews - private let reblogLabel = UILabel().configure { + 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) @@ -34,13 +26,6 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell { // $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(reblogLabelPressed))) } - private let reblogSpacer = UIView().configure { - $0.backgroundColor = nil - NSLayoutConstraint.activate([ - $0.heightAnchor.constraint(equalToConstant: 4), - ]) - } - private lazy var mainContainer = UIView().configure { avatarImageView.translatesAutoresizingMaskIntoConstraints = false $0.addSubview(avatarImageView) @@ -58,15 +43,15 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell { metaIndicatorsView.leadingAnchor.constraint(greaterThanOrEqualTo: $0.leadingAnchor), metaIndicatorsView.trailingAnchor.constraint(equalTo: avatarImageView.trailingAnchor), metaIndicatorsView.topAnchor.constraint(equalTo: avatarImageView.bottomAnchor, constant: 4), - metaIndicatorsView.bottomAnchor.constraint(lessThanOrEqualTo: $0.bottomAnchor), ]) } - private let avatarImageView = UIImageView().configure { + private static let avatarImageViewSize: CGFloat = 50 + private let avatarImageView = CachedImageView(cache: .avatars).configure { $0.layer.masksToBounds = true NSLayoutConstraint.activate([ - $0.heightAnchor.constraint(equalToConstant: 50), - $0.widthAnchor.constraint(equalToConstant: 50), + $0.heightAnchor.constraint(equalToConstant: TimelineStatusCollectionViewCell.avatarImageViewSize), + $0.widthAnchor.constraint(equalToConstant: TimelineStatusCollectionViewCell.avatarImageViewSize), ]) // TODO: context menu // $0.addInteraction(UIContextMenuInteraction(delegate: self)) @@ -136,7 +121,7 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell { ]), size: 0) } - private lazy var contentWarningLabel = UILabel().configure { + private lazy var contentWarningLabel = EmojiLabel().configure { $0.textColor = .secondaryLabel $0.font = UIFont(descriptor: .preferredFontDescriptor(withTextStyle: .body).addingAttributes([ .traits: [ @@ -155,7 +140,6 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell { }()).configure { $0.setContentHuggingPriority(.defaultHigh, for: .vertical) $0.addTarget(self, action: #selector(collapseButtonPressed), for: .touchUpInside) - // TODO: masksToBounds and cornerRadius? } private let contentContainer = StatusContentContainer().configure { @@ -227,26 +211,75 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell { $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 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) - vStack.translatesAutoresizingMaskIntoConstraints = false - contentView.addSubview(vStack) + 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([ - vStack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), - vStack.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), - vStack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8), - vStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8), + // 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 @@ -272,29 +305,187 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell { override func layoutSubviews() { super.layoutSubviews() - // 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 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 let status = mastodonController.persistentContainer.status(for: statusID) else { + guard var status = mastodonController.persistentContainer.status(for: statusID) else { fatalError() } - self.statusID = statusID + self.statusState = state - // TODO: remove this hack - state.collapsible = true - state.collapsed = state.collapsed ?? false -// state.resolveFor(status: status, text: "") - print("updateUI setting collapsed to: \(state.collapsed!)") - contentContainer.setCollapsed(state.collapsed!) - collapseButton.imageView!.transform = CGAffineTransform(rotationAngle: state.collapsed! ? .pi : 0) + + 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