Impressia/Vernissage/Views/StatusesView.swift

419 lines
16 KiB
Swift
Raw Normal View History

2023-01-21 18:01:17 +01:00
//
// https://mczachurski.dev
2023-04-09 20:51:33 +02:00
// Copyright © 2023 Marcin Czachurski and the repository contributors.
2023-03-28 10:35:38 +02:00
// Licensed under the Apache License 2.0.
2023-01-21 18:01:17 +01:00
//
import SwiftUI
import Nuke
2023-02-19 10:32:38 +01:00
import PixelfedKit
2023-04-07 14:20:12 +02:00
import ClientKit
2023-04-07 14:38:50 +02:00
import ServicesKit
2023-04-07 16:59:18 +02:00
import EnvironmentKit
import WidgetsKit
2023-01-21 18:01:17 +01:00
2023-10-19 13:24:02 +02:00
@MainActor
2023-01-23 08:43:04 +01:00
struct StatusesView: View {
2023-01-23 18:01:27 +01:00
public enum ListType: Hashable {
2023-05-26 16:06:38 +02:00
case home
2023-01-23 08:43:04 +01:00
case local
case federated
case favourites
case bookmarks
2023-01-23 18:01:27 +01:00
case hashtag(tag: String)
2023-04-20 15:03:43 +02:00
public var title: LocalizedStringKey {
switch self {
2023-05-26 16:06:38 +02:00
case .home:
return "mainview.tab.homeTimeline"
2023-04-20 15:03:43 +02:00
case .local:
return "statuses.navigationBar.localTimeline"
case .federated:
return "statuses.navigationBar.federatedTimeline"
case .favourites:
return "statuses.navigationBar.favourites"
case .bookmarks:
return "statuses.navigationBar.bookmarks"
case .hashtag(let tag):
return "#\(tag)"
}
}
2023-01-23 08:43:04 +01:00
}
2023-10-19 13:24:02 +02:00
@Environment(ApplicationState.self) var applicationState
@Environment(Client.self) var client
@Environment(RouterPath.self) var routerPath
2023-01-23 18:01:27 +01:00
2023-10-20 07:45:18 +02:00
@Environment(\.modelContext) private var modelContext
2023-03-07 16:45:44 +01:00
@Environment(\.dismiss) private var dismiss
2023-01-23 08:43:04 +01:00
@State public var listType: ListType
2023-01-21 18:01:17 +01:00
@State private var allItemsLoaded = false
2023-01-25 15:39:04 +01:00
@State private var tag: Tag?
@State private var statusViewModels: [StatusModel] = []
2023-02-01 18:40:28 +01:00
@State private var state: ViewState = .loading
@State private var lastStatusId: String?
2023-10-08 11:35:45 +02:00
@State private var waterfallId: String = String.randomString(length: 8)
2023-05-25 17:33:04 +02:00
// Gallery parameters.
@State private var imageColumns = 3
2023-09-22 15:22:48 +02:00
@State private var containerWidth: Double = UIDevice.isIPad ? UIScreen.main.bounds.width / 3 : UIScreen.main.bounds.width
@State private var containerHeight: Double = UIDevice.isIPad ? UIScreen.main.bounds.height / 3 : UIScreen.main.bounds.height
2023-05-25 17:33:04 +02:00
private let defaultLimit = 40
private let imagePrefetcher = ImagePrefetcher(destination: .diskCache)
2023-01-21 18:01:17 +01:00
var body: some View {
2023-02-01 18:40:28 +01:00
self.mainBody()
2023-04-20 15:03:43 +02:00
.navigationTitle(self.listType.title)
2023-02-01 18:40:28 +01:00
.toolbar {
2023-09-26 20:01:58 +02:00
self.getTrailingToolbar()
2023-02-01 18:40:28 +01:00
}
}
2023-02-01 18:40:28 +01:00
@ViewBuilder
private func mainBody() -> some View {
switch state {
case .loading:
LoadingIndicator()
.task {
await self.loadData()
}
case .loaded:
if self.statusViewModels.isEmpty {
2023-03-13 13:53:36 +01:00
NoDataView(imageSystemName: "photo.on.rectangle.angled", text: "statuses.title.noPhotos")
2023-02-01 18:40:28 +01:00
} else {
self.list()
2023-01-21 18:01:17 +01:00
}
2023-02-01 18:40:28 +01:00
case .error(let error):
ErrorView(error: error) {
self.state = .loading
await self.loadData()
}
.padding()
2023-01-21 18:01:17 +01:00
}
2023-02-01 18:40:28 +01:00
}
@ViewBuilder
private func list() -> some View {
ScrollView {
2023-05-25 17:33:04 +02:00
if self.imageColumns > 1 {
2023-10-08 11:35:45 +02:00
WaterfallGrid($statusViewModels, refreshId: $waterfallId, columns: $imageColumns, hideLoadMore: $allItemsLoaded) { item in
2023-05-25 17:33:04 +02:00
ImageRowAsync(statusViewModel: item, containerWidth: $containerWidth)
} onLoadMore: {
do {
try await self.loadMoreStatuses()
} catch {
ErrorService.shared.handle(error, message: "statuses.error.loadingStatusesFailed", showToastr: !Task.isCancelled)
}
}
} else {
LazyVStack(alignment: .center) {
ForEach(self.statusViewModels, id: \.id) { item in
ImageRowAsync(statusViewModel: item, containerWidth: $containerWidth)
}
if allItemsLoaded == false {
HStack {
Spacer()
LoadingIndicator()
.task {
do {
try await self.loadMoreStatuses()
} catch {
ErrorService.shared.handle(error, message: "statuses.error.loadingStatusesFailed", showToastr: !Task.isCancelled)
}
}
Spacer()
}
}
}
}
2023-05-25 17:33:04 +02:00
}
.gallery { galleryProperties in
self.imageColumns = galleryProperties.imageColumns
self.containerWidth = galleryProperties.containerWidth
self.containerHeight = galleryProperties.containerHeight
}
.refreshable {
do {
HapticService.shared.fireHaptic(of: .dataRefresh(intensity: 0.3))
2023-10-20 17:35:11 +02:00
try await self.refreshStatuses()
HapticService.shared.fireHaptic(of: .dataRefresh(intensity: 0.7))
} catch {
ErrorService.shared.handle(error, message: "statuses.error.loadingStatusesFailed", showToastr: !Task.isCancelled)
}
}
2023-10-19 09:29:49 +02:00
.onChange(of: self.applicationState.showReboostedStatuses) {
2023-10-08 11:35:45 +02:00
if self.listType != .home {
return
}
Task { @MainActor in
HapticService.shared.fireHaptic(of: .dataRefresh(intensity: 0.3))
2023-10-20 17:35:11 +02:00
try await self.refreshStatuses()
2023-10-08 11:35:45 +02:00
HapticService.shared.fireHaptic(of: .dataRefresh(intensity: 0.7))
}
}
}
2023-02-01 18:40:28 +01:00
private func loadData() async {
do {
try await self.loadStatuses()
2023-01-25 15:39:04 +01:00
2023-02-01 18:40:28 +01:00
if case .hashtag(let hashtag) = self.listType {
await self.loadTag(hashtag: hashtag)
2023-01-21 18:01:17 +01:00
}
withAnimation {
self.state = .loaded
}
2023-02-01 18:40:28 +01:00
} catch {
2023-03-13 13:53:36 +01:00
ErrorService.shared.handle(error, message: "statuses.error.loadingStatusesFailed", showToastr: !Task.isCancelled)
2023-02-01 18:40:28 +01:00
self.state = .error(error)
2023-01-21 18:01:17 +01:00
}
}
2023-01-21 18:01:17 +01:00
private func loadStatuses() async throws {
2023-10-20 17:35:11 +02:00
guard let accountId = self.applicationState.account?.id else {
return
}
2023-02-01 20:01:18 +01:00
let statuses = try await self.loadFromApi()
2023-11-20 15:23:42 +01:00
if statuses.data.isEmpty {
2023-02-01 20:01:18 +01:00
self.allItemsLoaded = true
2023-01-21 18:01:17 +01:00
return
}
// Remember last status id returned by API.
2023-11-20 15:23:42 +01:00
self.lastStatusId = statuses.getMaxId()
2023-10-20 17:35:11 +02:00
// Get only visible statuses.
let visibleStatuses = HomeTimelineService.shared.getVisibleStatuses(accountId: accountId,
2023-11-20 15:23:42 +01:00
statuses: statuses.data,
2023-10-20 17:35:11 +02:00
hideStatusesWithoutAlt: self.applicationState.hideStatusesWithoutAlt,
modelContext: modelContext)
if self.listType == .home {
// Remeber first status returned by API in user context (when it's newer then remembered).
2023-10-22 10:09:02 +02:00
try AccountDataHandler.shared.update(lastSeenStatusId: nil,
2023-11-20 15:23:42 +01:00
lastLoadedStatusId: statuses.getMinId(),
2023-10-22 10:09:02 +02:00
applicationState: self.applicationState,
modelContext: modelContext)
2023-10-10 10:10:24 +02:00
2023-10-20 17:35:11 +02:00
// Append statuses to viewed.
2023-11-20 15:23:42 +01:00
try ViewedStatusHandler.shared.append(contentsOf: statuses.data, accountId: accountId, modelContext: modelContext)
2023-01-21 18:01:17 +01:00
}
2023-10-20 17:35:11 +02:00
// Map to view models.
let statusModels = visibleStatuses.map({ StatusModel(status: $0) })
// Prefetch images.
2023-10-20 17:35:11 +02:00
self.prefetch(statusModels: statusModels)
// Append to empty list.
2023-10-20 17:35:11 +02:00
self.statusViewModels.append(contentsOf: statusModels)
2023-01-21 18:01:17 +01:00
}
2023-01-21 18:01:17 +01:00
private func loadMoreStatuses() async throws {
2023-10-20 17:35:11 +02:00
if let lastStatusId = self.lastStatusId, let accountId = self.applicationState.account?.id {
let statuses = try await self.loadFromApi(maxId: lastStatusId)
2023-01-21 18:01:17 +01:00
2023-11-20 15:23:42 +01:00
if statuses.data.isEmpty {
2023-01-21 18:01:17 +01:00
self.allItemsLoaded = true
2023-02-01 20:01:18 +01:00
return
2023-01-21 18:01:17 +01:00
}
// Now we have new last status.
2023-11-20 15:23:42 +01:00
if let lastStatusId = statuses.getMaxId() {
self.lastStatusId = lastStatusId
}
2023-10-20 17:35:11 +02:00
// Get only visible statuses.
let visibleStatuses = HomeTimelineService.shared.getVisibleStatuses(accountId: accountId,
2023-11-20 15:23:42 +01:00
statuses: statuses.data,
2023-10-20 17:35:11 +02:00
hideStatusesWithoutAlt: self.applicationState.hideStatusesWithoutAlt,
modelContext: modelContext)
2023-10-10 10:10:24 +02:00
2023-10-20 17:35:11 +02:00
if self.listType == .home {
// Append statuses to viewed.
2023-11-20 15:23:42 +01:00
try ViewedStatusHandler.shared.append(contentsOf: statuses.data, accountId: accountId, modelContext: modelContext)
2023-01-21 18:01:17 +01:00
}
2023-10-20 17:35:11 +02:00
// Map to view models.
let statusModels = visibleStatuses.map({ StatusModel(status: $0) })
// Prefetch images.
2023-10-20 17:35:11 +02:00
self.prefetch(statusModels: statusModels)
// Append statuses to existing array of statuses (at the end).
2023-10-20 17:35:11 +02:00
self.statusViewModels.append(contentsOf: statusModels)
2023-01-21 18:01:17 +01:00
}
}
2023-10-20 17:35:11 +02:00
private func refreshStatuses() async throws {
guard let accountId = self.applicationState.account?.id else {
return
}
let statuses = try await self.loadFromApi()
2023-11-20 15:23:42 +01:00
if statuses.data.isEmpty {
self.allItemsLoaded = true
return
}
// Remember last status id returned by API.
2023-11-20 15:23:42 +01:00
self.lastStatusId = statuses.getMaxId()
2023-10-20 17:35:11 +02:00
// Get only visible statuses.
let visibleStatuses = HomeTimelineService.shared.getVisibleStatuses(accountId: accountId,
2023-11-20 15:23:42 +01:00
statuses: statuses.data,
2023-10-20 17:35:11 +02:00
hideStatusesWithoutAlt: self.applicationState.hideStatusesWithoutAlt,
modelContext: modelContext)
if self.listType == .home {
// Remeber first status returned by API in user context (when it's newer then remembered).
2023-10-22 10:09:02 +02:00
try AccountDataHandler.shared.update(lastSeenStatusId: self.statusViewModels.first?.id,
2023-11-20 15:23:42 +01:00
lastLoadedStatusId: statuses.getMinId(),
2023-10-22 10:09:02 +02:00
applicationState: self.applicationState,
modelContext: modelContext)
2023-10-20 17:35:11 +02:00
// Append statuses to viewed.
2023-11-20 15:23:42 +01:00
try ViewedStatusHandler.shared.append(contentsOf: statuses.data, accountId: accountId, modelContext: modelContext)
2023-01-21 18:01:17 +01:00
}
2023-10-08 11:35:45 +02:00
2023-10-20 17:35:11 +02:00
// Map to view models.
let statusModels = visibleStatuses.map({ StatusModel(status: $0) })
2023-10-08 11:35:45 +02:00
// Prefetch images.
2023-10-20 17:35:11 +02:00
self.prefetch(statusModels: statusModels)
// Replace old collection with new one.
2023-10-08 11:35:45 +02:00
self.waterfallId = String.randomString(length: 8)
2023-10-20 17:35:11 +02:00
self.statusViewModels = statusModels
2023-01-21 18:01:17 +01:00
}
2023-11-20 15:23:42 +01:00
private func loadFromApi(maxId: String? = nil, sinceId: String? = nil, minId: String? = nil) async throws -> Linkable<[Status]> {
2023-01-23 08:43:04 +01:00
switch self.listType {
2023-05-26 16:06:38 +02:00
case .home:
return try await self.client.publicTimeline?.getHomeTimeline(
maxId: maxId,
sinceId: sinceId,
minId: minId,
limit: self.defaultLimit,
2023-11-20 15:23:42 +01:00
includeReblogs: self.applicationState.showReboostedStatuses) ?? Linkable(data: [])
2023-01-23 08:43:04 +01:00
case .local:
2023-02-03 15:16:30 +01:00
return try await self.client.publicTimeline?.getStatuses(
2023-01-23 08:43:04 +01:00
local: true,
maxId: maxId,
sinceId: sinceId,
minId: minId,
2023-11-20 15:23:42 +01:00
limit: self.defaultLimit) ?? Linkable(data: [])
2023-01-23 08:43:04 +01:00
case .federated:
2023-02-03 15:16:30 +01:00
return try await self.client.publicTimeline?.getStatuses(
2023-01-23 08:43:04 +01:00
remote: true,
maxId: maxId,
sinceId: sinceId,
minId: minId,
2023-11-20 15:23:42 +01:00
limit: self.defaultLimit) ?? Linkable(data: [])
2023-01-23 08:43:04 +01:00
case .favourites:
2023-11-20 15:23:42 +01:00
let favourites = try await self.client.accounts?.favourites(
2023-01-23 08:43:04 +01:00
maxId: maxId,
sinceId: sinceId,
minId: minId,
2023-02-03 15:16:30 +01:00
limit: self.defaultLimit) ?? []
2023-11-20 15:23:42 +01:00
return Linkable(data: favourites)
2023-01-23 08:43:04 +01:00
case .bookmarks:
2023-11-20 15:23:42 +01:00
let bookmarks = try await self.client.accounts?.bookmarks(
2023-01-23 08:43:04 +01:00
maxId: maxId,
sinceId: sinceId,
minId: minId,
2023-02-03 15:16:30 +01:00
limit: self.defaultLimit) ?? []
2023-11-20 15:23:42 +01:00
return Linkable(data: bookmarks)
2023-01-23 18:01:27 +01:00
case .hashtag(let tag):
2023-03-07 16:45:44 +01:00
let hashtagsFromApi = try await self.client.search?.search(query: tag, resultsType: .hashtags)
guard let hashtagsFromApi = hashtagsFromApi, hashtagsFromApi.hashtags.isEmpty == false else {
2023-10-18 11:14:56 +02:00
ToastrService.shared.showError(title: LocalizedStringResource("global.error.hashtagNotExists"), imageSystemName: "exclamationmark.octagon")
2023-03-07 16:45:44 +01:00
dismiss()
2023-11-20 15:23:42 +01:00
return Linkable(data: [])
2023-03-07 16:45:44 +01:00
}
2023-02-03 15:16:30 +01:00
return try await self.client.publicTimeline?.getTagStatuses(
2023-01-23 18:01:27 +01:00
tag: tag,
maxId: maxId,
sinceId: sinceId,
minId: minId,
2023-11-20 15:23:42 +01:00
limit: self.defaultLimit) ?? Linkable(data: [])
2023-01-23 08:43:04 +01:00
}
}
2023-01-25 15:39:04 +01:00
@ToolbarContentBuilder
private func getTrailingToolbar() -> some ToolbarContent {
if case .hashtag(let hashtag) = self.listType {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
Task {
if self.tag?.following == true {
await self.unfollow(hashtag: hashtag)
2023-09-26 20:01:58 +02:00
} else {
await self.follow(hashtag: hashtag)
2023-01-25 15:39:04 +01:00
}
}
} label: {
Image(systemName: self.tag?.following == true ? "number.square.fill" : "number.square")
.tint(.mainTextColor)
}
2023-09-26 20:01:58 +02:00
.disabled(self.tag == nil)
2023-01-25 15:39:04 +01:00
}
}
}
2023-01-25 15:39:04 +01:00
private func loadTag(hashtag: String) async {
do {
2023-02-03 15:16:30 +01:00
self.tag = try await self.client.tags?.get(tag: hashtag)
2023-01-25 15:39:04 +01:00
} catch {
2023-03-13 13:53:36 +01:00
ErrorService.shared.handle(error, message: "global.error.errorDuringDownloadHashtag", showToastr: false)
2023-01-25 15:39:04 +01:00
}
}
2023-01-25 15:39:04 +01:00
private func follow(hashtag: String) async {
do {
2023-02-03 15:16:30 +01:00
self.tag = try await self.client.tags?.follow(tag: hashtag)
2023-03-13 13:53:36 +01:00
ToastrService.shared.showSuccess("statuses.title.tagFollowed", imageSystemName: "number.square.fill")
2023-01-25 15:39:04 +01:00
} catch {
2023-03-13 13:53:36 +01:00
ErrorService.shared.handle(error, message: "statuses.error.tagFollowFailed", showToastr: true)
2023-01-25 15:39:04 +01:00
}
}
2023-01-25 15:39:04 +01:00
private func unfollow(hashtag: String) async {
do {
2023-02-03 15:16:30 +01:00
self.tag = try await self.client.tags?.unfollow(tag: hashtag)
2023-03-13 13:53:36 +01:00
ToastrService.shared.showSuccess("statuses.title.tagUnfollowed", imageSystemName: "number.square")
2023-01-25 15:39:04 +01:00
} catch {
2023-03-13 13:53:36 +01:00
ErrorService.shared.handle(error, message: "statuses.error.tagUnfollowFailed", showToastr: true)
2023-01-25 15:39:04 +01:00
}
}
private func prefetch(statusModels: [StatusModel]) {
imagePrefetcher.startPrefetching(with: statusModels.getAllImagesUrls())
}
2023-10-10 13:30:53 +02:00
private func shouldHideStatusWithoutAlt(status: Status) -> Bool {
if self.applicationState.hideStatusesWithoutAlt == false {
return false
}
if self.listType != .home && self.listType != .local && self.listType != .federated {
return false
}
return status.statusContainsAltText() == false
}
2023-01-21 18:01:17 +01:00
}