IceCubesApp/Packages/Account/Sources/Account/Follow/FollowButton.swift

97 lines
2.6 KiB
Swift
Raw Normal View History

2022-12-23 15:21:31 +00:00
import Foundation
import Models
import Network
2023-01-17 10:36:01 +00:00
import SwiftUI
2022-12-23 15:21:31 +00:00
@MainActor
public class FollowButtonViewModel: ObservableObject {
var client: Client?
2023-01-17 10:36:01 +00:00
2022-12-23 15:21:31 +00:00
public let accountId: String
public let shouldDisplayNotify: Bool
2023-01-17 10:36:01 +00:00
@Published public private(set) var relationship: Relationshionship
@Published public private(set) var isUpdating: Bool = false
public init(accountId: String, relationship: Relationshionship, shouldDisplayNotify: Bool) {
2022-12-23 15:21:31 +00:00
self.accountId = accountId
self.relationship = relationship
self.shouldDisplayNotify = shouldDisplayNotify
2022-12-23 15:21:31 +00:00
}
2023-01-17 10:36:01 +00:00
2022-12-23 15:21:31 +00:00
func follow() async {
guard let client else { return }
isUpdating = true
do {
relationship = try await client.post(endpoint: Accounts.follow(id: accountId, notify: false))
2022-12-23 15:21:31 +00:00
} catch {
print("Error while following: \(error.localizedDescription)")
}
isUpdating = false
}
2023-01-17 10:36:01 +00:00
2022-12-23 15:21:31 +00:00
func unfollow() async {
guard let client else { return }
isUpdating = true
do {
relationship = try await client.post(endpoint: Accounts.unfollow(id: accountId))
} catch {
print("Error while unfollowing: \(error.localizedDescription)")
}
isUpdating = false
}
2023-01-17 10:36:01 +00:00
func toggleNotify() async {
guard let client else { return }
do {
relationship = try await client.post(endpoint: Accounts.follow(id: accountId, notify: !relationship.notifying))
} catch {
print("Error while following: \(error.localizedDescription)")
}
}
2022-12-23 15:21:31 +00:00
}
public struct FollowButton: View {
@EnvironmentObject private var client: Client
@StateObject private var viewModel: FollowButtonViewModel
2023-01-17 10:36:01 +00:00
2022-12-23 15:21:31 +00:00
public init(viewModel: FollowButtonViewModel) {
_viewModel = StateObject(wrappedValue: viewModel)
}
2023-01-17 10:36:01 +00:00
2022-12-23 15:21:31 +00:00
public var body: some View {
HStack {
Button {
Task {
if viewModel.relationship.following {
await viewModel.unfollow()
} else {
await viewModel.follow()
}
}
} label: {
if viewModel.relationship.requested == true {
Text("Requested")
2022-12-23 15:21:31 +00:00
} else {
Text(viewModel.relationship.following ? "Following" : "Follow")
2022-12-23 15:21:31 +00:00
}
}
.buttonStyle(.bordered)
.disabled(viewModel.isUpdating)
if viewModel.relationship.following, viewModel.shouldDisplayNotify {
Button {
Task {
await viewModel.toggleNotify()
}
} label: {
Image(systemName: viewModel.relationship.notifying ? "bell.fill" : "bell")
}
.buttonStyle(.bordered)
.disabled(viewModel.isUpdating)
2022-12-23 15:21:31 +00:00
}
}
.onAppear {
viewModel.client = client
}
}
}