Compare commits

..

3 Commits

7 changed files with 683 additions and 102 deletions

View File

@ -36,6 +36,7 @@
D61A45E628DC0F2F002BE511 /* ConfirmLoadMoreCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = D61A45E528DC0F2F002BE511 /* ConfirmLoadMoreCollectionViewCell.swift */; };
D61A45E828DF477D002BE511 /* LoadingCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = D61A45E728DF477D002BE511 /* LoadingCollectionViewCell.swift */; };
D61A45EA28DF51EE002BE511 /* TimelineLikeCollectionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D61A45E928DF51EE002BE511 /* TimelineLikeCollectionViewController.swift */; };
D61ABEF628EE74D400B29151 /* StatusCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = D61ABEF528EE74D400B29151 /* StatusCollectionViewCell.swift */; };
D61AC1D5232E9FA600C54D2D /* InstanceSelectorTableViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D61AC1D4232E9FA600C54D2D /* InstanceSelectorTableViewController.swift */; };
D61AC1D8232EA42D00C54D2D /* InstanceTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = D61AC1D6232EA42D00C54D2D /* InstanceTableViewCell.swift */; };
D61AC1D9232EA42D00C54D2D /* InstanceTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = D61AC1D7232EA42D00C54D2D /* InstanceTableViewCell.xib */; };
@ -219,6 +220,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 */; };
@ -386,6 +388,7 @@
D61A45E528DC0F2F002BE511 /* ConfirmLoadMoreCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfirmLoadMoreCollectionViewCell.swift; sourceTree = "<group>"; };
D61A45E728DF477D002BE511 /* LoadingCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoadingCollectionViewCell.swift; sourceTree = "<group>"; };
D61A45E928DF51EE002BE511 /* TimelineLikeCollectionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimelineLikeCollectionViewController.swift; sourceTree = "<group>"; };
D61ABEF528EE74D400B29151 /* StatusCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusCollectionViewCell.swift; sourceTree = "<group>"; };
D61AC1D4232E9FA600C54D2D /* InstanceSelectorTableViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InstanceSelectorTableViewController.swift; sourceTree = "<group>"; };
D61AC1D6232EA42D00C54D2D /* InstanceTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InstanceTableViewCell.swift; sourceTree = "<group>"; };
D61AC1D7232EA42D00C54D2D /* InstanceTableViewCell.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = InstanceTableViewCell.xib; sourceTree = "<group>"; };
@ -568,6 +571,7 @@
D6ADB6E928E91C30009924AB /* TimelineStatusCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimelineStatusCollectionViewCell.swift; sourceTree = "<group>"; };
D6ADB6EB28EA73CB009924AB /* StatusContentContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusContentContainer.swift; sourceTree = "<group>"; };
D6ADB6ED28EA74E8009924AB /* UIView+Configure.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIView+Configure.swift"; sourceTree = "<group>"; };
D6ADB6EF28ED1F25009924AB /* CachedImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CachedImageView.swift; sourceTree = "<group>"; };
D6AEBB3D2321638100E5038B /* UIActivity+Types.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIActivity+Types.swift"; sourceTree = "<group>"; };
D6AEBB402321642700E5038B /* SendMesasgeActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SendMesasgeActivity.swift; sourceTree = "<group>"; };
D6AEBB422321685E00E5038B /* OpenInSafariActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenInSafariActivity.swift; sourceTree = "<group>"; };
@ -1028,6 +1032,7 @@
D6C1B2072545D1EC00DAAA66 /* StatusCardView.swift */,
D6EE63FA2551F7F60065485C /* StatusCollapseButton.swift */,
D62E9986279D094F00C26176 /* StatusMetaIndicatorsView.swift */,
D61ABEF528EE74D400B29151 /* StatusCollectionViewCell.swift */,
D6ADB6E928E91C30009924AB /* TimelineStatusCollectionViewCell.swift */,
D6ADB6EB28EA73CB009924AB /* StatusContentContainer.swift */,
);
@ -1255,6 +1260,7 @@
children = (
D6B4A4FE2506B81A000C81C1 /* AccountDisplayNameLabel.swift */,
D68E6F5E253C9B2D001A1B4C /* BaseEmojiLabel.swift */,
D6ADB6EF28ED1F25009924AB /* CachedImageView.swift */,
D6895DC328D65342006341DA /* ConfirmReblogStatusPreviewView.swift */,
D620483523D38075008A63EF /* ContentTextView.swift */,
D6E426B225337C7000C02E1C /* CustomEmojiImageView.swift */,
@ -1756,6 +1762,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 */,
@ -1833,6 +1840,7 @@
D6A6C11B25B63CEE00298D0F /* MemoryCache.swift in Sources */,
D6114E0D27F7FEB30080E273 /* TrendingStatusesViewController.swift in Sources */,
D6BC9DDA232D8BE5002CA326 /* SearchResultsViewController.swift in Sources */,
D61ABEF628EE74D400B29151 /* StatusCollectionViewCell.swift in Sources */,
D627FF7F217E95E000CC0648 /* DraftTableViewCell.swift in Sources */,
D6B17255254F88B800128392 /* OppositeCollapseKeywordsView.swift in Sources */,
D6A00B1D26379FC900316AD4 /* PollOptionsView.swift in Sources */,

View File

@ -149,6 +149,10 @@ class TimelineViewController: UIViewController, TimelineLikeCollectionViewContro
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView.indexPathsForSelectedItems?.forEach {
collectionView.deselectItem(at: $0, animated: true)
}
Task {
await controller.loadInitial()
}
@ -220,6 +224,15 @@ extension TimelineViewController {
return false
}
}
var isSelectable: Bool {
switch self {
case .publicTimelineDescription, .status(id: _, state: _):
return true
default:
return false
}
}
}
}
@ -310,6 +323,10 @@ extension TimelineViewController: UICollectionViewDelegate {
}
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return dataSource.itemIdentifier(for: indexPath)?.isSelectable ?? false
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath) else {
return
@ -317,10 +334,10 @@ extension TimelineViewController: UICollectionViewDelegate {
switch item {
case .publicTimelineDescription:
removeTimelineDescriptionCell()
default:
// TODO: cell selection
break
case .status(id: let id, state: let state):
selected(status: id, state: state.copy())
case .loadingIndicator, .confirmLoadMore:
fatalError("unreachable")
}
}
@ -331,11 +348,19 @@ extension TimelineViewController: UICollectionViewDelegate {
}
}
extension TimelineViewController: TimelineStatusCollectionViewCellDelegate {
func statusCellCollapsedStateChanged(_ cell: TimelineStatusCollectionViewCell) {
let indexPath = collectionView.indexPath(for: cell)!
extension TimelineViewController: TuskerNavigationDelegate {
var apiController: MastodonController { mastodonController }
}
extension TimelineViewController: MenuActionProvider {
}
extension TimelineViewController: StatusCollectionViewCellDelegate {
func statusCellNeedsReconfigure(_ cell: StatusCollectionViewCell, animated: Bool) {
if let indexPath = collectionView.indexPath(for: cell) {
var snapshot = dataSource.snapshot()
snapshot.reconfigureItems([dataSource.itemIdentifier(for: indexPath)!])
dataSource.apply(snapshot, animatingDifferences: true)
dataSource.apply(snapshot, animatingDifferences: animated)
}
}
}

View File

@ -409,6 +409,21 @@ extension MenuActionProvider {
}
struct MenuPreviewHelper {
static func willPerformPreviewAction(animator: UIContextMenuInteractionCommitAnimating, presenter: UIViewController) {
if let viewController = animator.previewViewController {
animator.preferredCommitStyle = .pop
animator.addCompletion {
if let customPresenting = viewController as? CustomPreviewPresenting {
customPresenting.presentFromPreview(presenter: presenter)
} else {
presenter.show(viewController, sender: nil)
}
}
}
}
}
extension LargeImageViewController: CustomPreviewPresenting {
func presentFromPreview(presenter: UIViewController) {
presenter.present(self, animated: true)

View File

@ -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<Void, Error>?
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
}
}
}

View File

@ -0,0 +1,269 @@
//
// StatusCollectionViewCell.swift
// Tusker
//
// Created by Shadowfacts on 10/5/22.
// Copyright © 2022 Shadowfacts. All rights reserved.
//
import UIKit
import Pachyderm
@MainActor
protocol StatusCollectionViewCellDelegate: AnyObject, TuskerNavigationDelegate, MenuActionProvider {
func statusCellNeedsReconfigure(_ cell: StatusCollectionViewCell, animated: Bool)
}
@MainActor
protocol StatusCollectionViewCell: UICollectionViewCell {
// MARK: Subviews
var avatarImageView: CachedImageView { get }
var displayNameLabel: EmojiLabel { get }
var usernameLabel: UILabel { get }
var contentWarningLabel: EmojiLabel { get }
var collapseButton: UIButton { get }
var contentContainer: StatusContentContainer { get }
var replyButton: UIButton { get }
var favoriteButton: UIButton { get }
var reblogButton: UIButton { get }
var moreButton: UIButton { get }
// TODO: why is one of these ! and the other ?
var mastodonController: MastodonController! { get }
var delegate: StatusCollectionViewCellDelegate? { get }
var showStatusAutomatically: Bool { get }
var showReplyIndicator: Bool { get }
var statusID: String! { get set }
var statusState: StatusState! { get set }
var accountID: String! { get set }
var isGrayscale: Bool { get set }
func updateUIForPreferences(status: StatusMO)
}
// MARK: UI Configuration
extension StatusCollectionViewCell {
static var avatarImageViewSize: CGFloat { 50 }
func doUpdateUI(status: StatusMO) {
statusID = status.id
accountID = status.account.id
let account = status.account
avatarImageView.update(for: account.avatar)
displayNameLabel.updateForAccountDisplayName(account: account)
usernameLabel.text = "@\(account.acct)"
contentContainer.contentTextView.setTextFrom(status: status)
updateUIForPreferences(status: status)
contentContainer.cardView.card = status.card
contentContainer.cardView.isHidden = status.card == nil
contentContainer.cardView.navigationDelegate = delegate
contentContainer.cardView.actionProvider = delegate
contentContainer.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 && mastodonController.loggedIn && accountID != mastodonController.account.id)
} else {
reblogDisabled = status.visibility == .direct || status.visibility == .private
}
reblogButton.isEnabled = !reblogDisabled && mastodonController.loggedIn
replyButton.isEnabled = mastodonController.loggedIn
favoriteButton.isEnabled = mastodonController.loggedIn
if statusState.unknown {
statusState.resolveFor(status: status, text: contentContainer.contentTextView.text)
if statusState.collapsible! && showStatusAutomatically {
statusState.collapsed = false
}
}
contentContainer.setCollapsed(statusState.collapsed!)
if statusState.collapsed! {
contentContainer.alpha = 0
// TODO: is this accessing the image view before the button's been laid out?
collapseButton.imageView!.transform = CGAffineTransform(rotationAngle: .pi)
collapseButton.accessibilityLabel = NSLocalizedString("Expand Status", comment: "expand status button accessibility label")
} else {
contentContainer.alpha = 1
collapseButton.imageView!.transform = CGAffineTransform(rotationAngle: 0)
collapseButton.accessibilityLabel = NSLocalizedString("Collapse Status", comment: "collapse status button accessibility label")
}
}
func baseUpdateUIForPreferences(status: StatusMO) {
avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadiusFraction * Self.avatarImageViewSize
contentContainer.attachmentsView.contentHidden = Preferences.shared.blurAllMedia || status.sensitive
}
// only called when isGrayscale does not match the pref
func updateGrayscaleableUI(status: StatusMO) {
isGrayscale = Preferences.shared.grayscaleImages
if contentContainer.contentTextView.hasEmojis {
contentContainer.contentTextView.setTextFrom(status: status)
}
displayNameLabel.updateForAccountDisplayName(account: status.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) ?? [])
contentContainer.pollView.isHidden = status.poll == nil
contentContainer.pollView.mastodonController = mastodonController
contentContainer.pollView.toastableViewController = delegate?.toastableViewController
contentContainer.pollView.updateUI(status: status, poll: status.poll)
}
}
// MARK: Interaction
extension StatusCollectionViewCell {
func toggleCollapse() {
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?.statusCellNeedsReconfigure(self, animated: true)
}
func toggleFavorite() {
guard let status = mastodonController.persistentContainer.status(for: statusID) else {
fatalError()
}
let oldValue = status.favourited
status.favourited.toggle()
// update ui before network request to make things appear speedy
updateStatusState(status: status)
let request = (status.favourited ? Status.favourite : Status.unfavourite)(statusID)
Task {
do {
let (newStatus, _) = try await mastodonController.run(request)
mastodonController.persistentContainer.addOrUpdate(status: newStatus)
// TODO: should this before the network request
UIImpactFeedbackGenerator(style: .light).impactOccurred()
} catch {
status.favourited = oldValue
// TODO: display error message
UINotificationFeedbackGenerator().notificationOccurred(.error)
}
}
}
func toggleReblog() {
guard let status = mastodonController.persistentContainer.status(for: statusID) else {
fatalError()
}
if !status.reblogged,
Preferences.shared.confirmBeforeReblog {
let image: UIImage?
let reblogVisibilityActions: [CustomAlertController.MenuAction]?
if mastodonController.instanceFeatures.reblogVisibility {
image = UIImage(systemName: Status.Visibility.public.unfilledImageName)
reblogVisibilityActions = [Status.Visibility.unlisted, .private].map { visibility in
CustomAlertController.MenuAction(title: "Reblog as \(visibility.displayName)", subtitle: visibility.subtitle, image: UIImage(systemName: visibility.unfilledImageName)) { [unowned self] in
self.doReblog(status: status, visibility: visibility)
}
}
} else {
image = nil
reblogVisibilityActions = []
}
let preview = ConfirmReblogStatusPreviewView(status: status)
var config = CustomAlertController.Configuration(title: "Are you sure you want to reblog this post?", content: preview, actions: [
CustomAlertController.Action(title: "Cancel", style: .cancel, handler: nil),
CustomAlertController.Action(title: "Reblog", image: image, style: .default, handler: { [unowned self] in
self.doReblog(status: status, visibility: nil)
})
])
if let reblogVisibilityActions {
var menuAction = CustomAlertController.Action(title: nil, image: UIImage(systemName: "chevron.down"), style: .menu(reblogVisibilityActions), handler: nil)
menuAction.isSecondaryMenu = true
config.actions.append(menuAction)
}
let alert = CustomAlertController(config: config)
delegate?.present(alert, animated: true)
} else {
doReblog(status: status, visibility: nil)
}
}
private func doReblog(status: StatusMO, visibility: Status.Visibility?) {
let oldValue = status.reblogged
status.reblogged.toggle()
updateStatusState(status: status)
let request: Request<Status>
if status.reblogged {
request = Status.reblog(statusID, visibility: visibility)
} else {
request = Status.unreblog(statusID)
}
Task {
do {
let (newStatus, _) = try await mastodonController.run(request)
mastodonController.persistentContainer.addOrUpdate(status: newStatus)
// TODO: should this before the network request
UIImpactFeedbackGenerator(style: .light).impactOccurred()
} catch {
status.reblogged = oldValue
// TODO: display error message
UINotificationFeedbackGenerator().notificationOccurred(.error)
}
}
}
}
extension StatusCollectionViewCell {
func contextMenuConfigurationForAccount(sourceView: UIView) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration() {
ProfileViewController(accountID: self.accountID, mastodonController: self.mastodonController)
} actionProvider: { _ in
return UIMenu(children: self.delegate?.actionsForProfile(accountID: self.accountID, sourceView: sourceView) ?? [])
}
}
}
extension StatusCollectionViewCell {
func dragItemsForAccount() -> [UIDragItem] {
guard let currentAccountID = mastodonController.accountInfo?.id,
let account = mastodonController.persistentContainer.account(for: accountID) else {
return []
}
let provider = NSItemProvider(object: account.url as NSURL)
let activity = UserActivityManager.showProfileActivity(id: accountID, accountID: currentAccountID)
activity.displaysAuxiliaryScene = true
provider.registerObject(activity, visibility: .all)
return [UIDragItem(itemProvider: provider)]
}
}

View File

@ -14,6 +14,8 @@ class StatusContentContainer: UIView {
$0.defaultFont = .systemFont(ofSize: 16)
$0.isScrollEnabled = false
$0.backgroundColor = nil
$0.isEditable = false
$0.isSelectable = false
}
let cardView = StatusCardView().configure {

View File

@ -9,36 +9,15 @@
import UIKit
import Pachyderm
@MainActor
protocol TimelineStatusCollectionViewCellDelegate: AnyObject {
func statusCellCollapsedStateChanged(_ cell: TimelineStatusCollectionViewCell)
}
class TimelineStatusCollectionViewCell: UICollectionViewListCell, StatusCollectionViewCell {
class TimelineStatusCollectionViewCell: UICollectionViewListCell {
// MARK: Subviews
private lazy var vStack = UIStackView(arrangedSubviews: [
reblogLabel,
reblogSpacer,
mainContainer,
actionsContainer,
]).configure {
$0.axis = .vertical
$0.alignment = .fill
}
private let reblogLabel = UILabel().configure {
private lazy var 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 let reblogSpacer = UIView().configure {
$0.backgroundColor = nil
NSLayoutConstraint.activate([
$0.heightAnchor.constraint(equalToConstant: 4),
])
$0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(reblogLabelPressed)))
}
private lazy var mainContainer = UIView().configure {
@ -58,22 +37,20 @@ 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(set) lazy var 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))
// TODO: drag gesture
// $0.addInteraction(UIDragInteraction(delegate: self))
// TODO: tap gesture
// $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
$0.isUserInteractionEnabled = true
$0.addInteraction(UIContextMenuInteraction(delegate: self))
$0.addInteraction(UIDragInteraction(delegate: self))
$0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
}
private let metaIndicatorsView = StatusMetaIndicatorsView()
@ -97,11 +74,10 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell {
]).configure {
$0.axis = .horizontal
$0.spacing = 4
// TODO: tap gesture
// $0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
$0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(accountPressed)))
}
private let displayNameLabel = EmojiLabel().configure {
let displayNameLabel = EmojiLabel().configure {
$0.font = UIFont(descriptor: .preferredFontDescriptor(withTextStyle: .body).addingAttributes([
.traits: [
UIFontDescriptor.TraitKey.weight: UIFont.Weight.semibold.rawValue,
@ -111,7 +87,7 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell {
$0.setContentCompressionResistancePriority(.init(749), for: .horizontal)
}
private let usernameLabel = UILabel().configure {
let usernameLabel = UILabel().configure {
$0.textColor = .secondaryLabel
$0.font = UIFont(descriptor: .preferredFontDescriptor(withTextStyle: .body).addingAttributes([
.traits: [
@ -136,7 +112,7 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell {
]), size: 0)
}
private lazy var contentWarningLabel = UILabel().configure {
private(set) lazy var contentWarningLabel = EmojiLabel().configure {
$0.textColor = .secondaryLabel
$0.font = UIFont(descriptor: .preferredFontDescriptor(withTextStyle: .body).addingAttributes([
.traits: [
@ -148,17 +124,18 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell {
$0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(collapseButtonPressed)))
}
private lazy var collapseButton = UIButton(configuration: {
private(set) lazy var collapseButton = UIButton(configuration: {
var config = UIButton.Configuration.filled()
config.image = UIImage(systemName: "chevron.down")
return config
}()).configure {
// this button is so big that dimming its background color is visually distracting
$0.tintAdjustmentMode = .normal
$0.setContentHuggingPriority(.defaultHigh, for: .vertical)
$0.addTarget(self, action: #selector(collapseButtonPressed), for: .touchUpInside)
// TODO: masksToBounds and cornerRadius?
}
private let contentContainer = StatusContentContainer().configure {
let contentContainer = StatusContentContainer().configure {
$0.setContentHuggingPriority(.defaultLow, for: .vertical)
}
private var contentTextView: StatusContentTextView {
@ -210,59 +187,97 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell {
])
}
private let replyButton = UIButton().configure {
private(set) lazy var replyButton = UIButton().configure {
$0.setImage(UIImage(systemName: "arrowshape.turn.up.left.fill"), for: .normal)
$0.addTarget(self, action: #selector(replyPressed), for: .touchUpInside)
}
private let favoriteButton = UIButton().configure {
private(set) lazy var favoriteButton = UIButton().configure {
$0.setImage(UIImage(systemName: "star.fill"), for: .normal)
$0.addTarget(self, action: #selector(favoritePressed), for: .touchUpInside)
}
private let reblogButton = UIButton().configure {
private(set) lazy var reblogButton = UIButton().configure {
$0.setImage(UIImage(systemName: "repeat"), for: .normal)
$0.addTarget(self, action: #selector(reblogPressed), for: .touchUpInside)
}
private let moreButton = UIButton().configure {
let moreButton = UIButton().configure {
$0.setImage(UIImage(systemName: "ellipsis"), for: .normal)
$0.showsMenuAsPrimaryAction = true
}
weak var mastodonController: MastodonController!
weak var delegate: TimelineStatusCollectionViewCellDelegate?
// MARK: Cell state
private(set) var statusID: String?
private(set) var statusState = StatusState.unknown
private var mainContainerTopToReblogLabelConstraint: NSLayoutConstraint!
private var mainContainerTopToSelfConstraint: NSLayoutConstraint!
private var mainContainerBottomToActionsConstraint: NSLayoutConstraint!
private var mainContainerBottomToSelfConstraint: NSLayoutConstraint!
weak var mastodonController: MastodonController!
weak var delegate: StatusCollectionViewCellDelegate?
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
}
// alas these need to be internal so they're accessible from the protocol extensions
var statusID: String!
var statusState: StatusState!
var accountID: String!
private var reblogStatusID: String?
private var rebloggerID: String?
private var firstLayout = true
var isGrayscale = false
private var updateTimestampWorkItem: DispatchWorkItem?
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,
])
// 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
updateActionsVisibility()
NotificationCenter.default.addObserver(self, selector: #selector(preferencesChanged), name: .preferencesChanged, object: nil)
}
required init?(coder: NSCoder) {
@ -272,37 +287,221 @@ class TimelineStatusCollectionViewCell: UICollectionViewListCell {
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
if firstLayout {
firstLayout = false
placeholderReplyButtonLeadingConstraint.isActive = false
replyButton.imageView!.leadingAnchor.constraint(equalTo: contentTextView.leadingAnchor).isActive = true
}
}
func updateUI(statusID: String, state: StatusState) {
// MARK: Accessibility
override var accessibilityLabel: String? {
get {
guard let status = mastodonController.persistentContainer.status(for: statusID) else {
return nil
}
var str = "\(status.account.displayOrUserName), \(contentTextView.text ?? "")"
if status.attachments.count > 0 {
// TODO: localize me
str += ", \(status.attachments.count) attachment\(status.attachments.count > 1 ? "s" : "")"
}
if status.poll != nil {
str += ", poll"
}
str += ", \(status.createdAt.formatted(.relative(presentation: .numeric)))"
if let rebloggerID,
let reblogger = mastodonController.persistentContainer.account(for: rebloggerID) {
str += ", reblogged by \(reblogger.displayOrUserName)"
}
return str
}
set {}
}
override func accessibilityActivate() -> Bool {
delegate?.selected(status: statusID, state: statusState.copy())
return true
}
// MARK: Configure UI
func updateUI(statusID: String, state: StatusState) {
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)
doUpdateTimestamp(status: status)
timestampLabel.isHidden = showPinned
pinImageView.isHidden = !showPinned
}
func updateUIForPreferences(status: StatusMO) {
baseUpdateUIForPreferences(status: status)
if showReplyIndicator {
metaIndicatorsView.allowedIndicators = .all
} else {
metaIndicatorsView.allowedIndicators = .all.subtracting(.reply)
}
if let rebloggerID,
let reblogger = mastodonController.persistentContainer.account(for: rebloggerID) {
updateRebloggerLabel(reblogger: reblogger)
}
}
private func updateTimestamp() {
guard let mastodonController,
let status = mastodonController.persistentContainer.status(for: statusID) else {
return
}
doUpdateTimestamp(status: status)
}
private func doUpdateTimestamp(status: StatusMO) {
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 {
if updateTimestampWorkItem == nil {
updateTimestampWorkItem = DispatchWorkItem { [weak self] in
self?.updateTimestamp()
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: updateTimestampWorkItem!)
} else {
updateTimestampWorkItem = nil
}
}
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)
}
}
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(status: status)
if isGrayscale != Preferences.shared.grayscaleImages {
updateGrayscaleableUI(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?.statusCellNeedsReconfigure(self, animated: true)
}
}
// 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)
@objc private func reblogLabelPressed() {
guard let rebloggerID else {
return
}
delegate?.selected(account: rebloggerID)
}
@objc private func accountPressed() {
delegate?.selected(account: accountID)
}
@objc private func collapseButtonPressed() {
toggleCollapse()
}
@objc private func replyPressed() {
if Preferences.shared.mentionReblogger,
let rebloggerID = rebloggerID,
let rebloggerAccount = mastodonController.persistentContainer.account(for: rebloggerID) {
delegate?.compose(inReplyToID: statusID, mentioningAcct: rebloggerAccount.acct)
} else {
delegate?.compose(inReplyToID: statusID)
}
}
@objc private func favoritePressed() {
toggleFavorite()
}
@objc private func reblogPressed() {
toggleReblog()
}
}
extension TimelineStatusCollectionViewCell: UIContextMenuInteractionDelegate {
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
return contextMenuConfigurationForAccount(sourceView: interaction.view!)
}
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
if let delegate {
MenuPreviewHelper.willPerformPreviewAction(animator: animator, presenter: delegate)
}
}
}
extension TimelineStatusCollectionViewCell: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
return dragItemsForAccount()
}
}