IceCubesApp/Packages/AppAccount/Sources/AppAccount/AppAccountsSelectorView.swift

104 lines
2.7 KiB
Swift
Raw Normal View History

import DesignSystem
2023-01-17 10:36:01 +00:00
import Env
import SwiftUI
public struct AppAccountsSelectorView: View {
@EnvironmentObject private var currentAccount: CurrentAccount
@EnvironmentObject private var appAccounts: AppAccountsManager
2023-01-17 10:36:01 +00:00
@ObservedObject var routeurPath: RouterPath
2023-01-17 10:36:01 +00:00
@State private var accountsViewModel: [AppAccountViewModel] = []
2023-01-17 10:36:01 +00:00
2023-01-16 12:39:35 +00:00
private let accountCreationEnabled: Bool
private let avatarSize: AvatarView.Size
2023-01-17 10:36:01 +00:00
2023-01-16 12:39:35 +00:00
public init(routeurPath: RouterPath,
accountCreationEnabled: Bool = true,
2023-01-17 10:36:01 +00:00
avatarSize: AvatarView.Size = .badge)
{
self.routeurPath = routeurPath
2023-01-16 12:39:35 +00:00
self.accountCreationEnabled = accountCreationEnabled
self.avatarSize = avatarSize
}
2023-01-17 10:36:01 +00:00
public var body: some View {
2023-01-16 20:27:54 +00:00
Group {
2023-01-16 21:01:04 +00:00
if UIDevice.current.userInterfaceIdiom == .pad {
2023-01-16 20:27:54 +00:00
labelView
.contextMenu {
menuView
}
} else {
Menu {
menuView
} label: {
labelView
}
}
2023-01-10 05:58:50 +00:00
}
.onAppear {
refreshAccounts()
}
.onChange(of: currentAccount.account?.id) { _ in
refreshAccounts()
}
}
2023-01-17 10:36:01 +00:00
2023-01-16 20:15:33 +00:00
@ViewBuilder
private var labelView: some View {
if let avatar = currentAccount.account?.avatar {
AvatarView(url: avatar, size: avatarSize)
} else {
EmptyView()
}
}
2023-01-17 10:36:01 +00:00
2023-01-16 20:15:33 +00:00
@ViewBuilder
private var menuView: some View {
ForEach(accountsViewModel, id: \.appAccount.id) { viewModel in
Section(viewModel.acct) {
Button {
if let account = currentAccount.account,
2023-01-17 10:36:01 +00:00
viewModel.account?.id == account.id
{
2023-01-16 20:15:33 +00:00
routeurPath.navigate(to: .accountDetailWithAccount(account: account))
} else {
appAccounts.currentAccount = viewModel.appAccount
}
} label: {
HStack {
if viewModel.account?.id == currentAccount.account?.id {
Image(systemName: "checkmark.circle.fill")
}
Text("\(viewModel.account?.displayName ?? "")")
}
}
}
}
if accountCreationEnabled {
Divider()
Button {
routeurPath.presentedSheet = .addAccount
} label: {
Label("Add Account", systemImage: "person.badge.plus")
}
}
}
2023-01-17 10:36:01 +00:00
private func refreshAccounts() {
if accountsViewModel.isEmpty || appAccounts.availableAccounts.count != accountsViewModel.count {
accountsViewModel = []
for account in appAccounts.availableAccounts {
let viewModel: AppAccountViewModel = .init(appAccount: account)
Task {
await viewModel.fetchAccount()
2023-01-16 20:27:54 +00:00
if !accountsViewModel.contains(where: { $0.acct == viewModel.acct }) {
accountsViewModel.append(viewModel)
}
}
}
}
}
}