Impressia/Vernissage/Views/SettingsView/Subviews/AccountsSectionView.swift

82 lines
3.0 KiB
Swift
Raw Normal View History

2023-01-13 13:37:01 +01:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
// Licensed under the MIT License.
//
import SwiftUI
2023-02-21 07:05:06 +01:00
struct AccountsSectionView: View {
2023-01-27 17:31:28 +01:00
@EnvironmentObject var applicationState: ApplicationState
2023-02-23 08:09:02 +01:00
@EnvironmentObject var client: Client
2023-01-27 17:31:28 +01:00
@State private var accounts: [AccountModel] = []
@State private var dbAccounts: [AccountData] = []
2023-01-13 13:37:01 +01:00
var body: some View {
Section("Accounts") {
ForEach(self.accounts) { account in
2023-01-27 17:31:28 +01:00
HStack(alignment: .center) {
UsernameRow(accountId: account.id,
accountAvatar: account.avatar,
accountDisplayName: account.displayName,
accountUsername: account.username)
Spacer()
if self.applicationState.account?.id == account.id {
2023-01-27 17:31:28 +01:00
Image(systemName: "checkmark")
.foregroundColor(self.applicationState.tintColor.color())
}
}
2023-02-23 08:09:02 +01:00
.deleteDisabled(self.deleteDisabled(for: account))
2023-01-13 13:37:01 +01:00
}
2023-01-27 17:31:28 +01:00
.onDelete(perform: delete)
2023-01-13 13:37:01 +01:00
2023-01-23 18:01:27 +01:00
NavigationLink(value: RouteurDestinations.signIn) {
2023-01-13 13:37:01 +01:00
HStack {
Text("New account")
Spacer()
Image(systemName: "person.crop.circle.badge.plus")
}
}
}
.onAppear {
self.dbAccounts = AccountDataHandler.shared.getAccountsData()
self.accounts = self.dbAccounts.map({ AccountModel(accountData: $0) })
}
2023-01-13 13:37:01 +01:00
}
2023-01-27 17:31:28 +01:00
2023-02-23 08:09:02 +01:00
private func deleteDisabled(for account: AccountModel) -> Bool {
self.applicationState.account?.id == account.id && self.accounts.count > 1
}
private func delete(at offsets: IndexSet) {
2023-01-27 17:31:28 +01:00
let accountsToDelete = offsets.map { self.accounts[$0] }
2023-02-23 08:09:02 +01:00
var shouldClearApplicationState = false
// Delete from database.
2023-01-27 17:31:28 +01:00
for account in accountsToDelete {
2023-02-23 08:09:02 +01:00
// Check if we are deleting active user.
if account.id == self.applicationState.account?.id {
shouldClearApplicationState = true
}
if let dbAccount = self.dbAccounts.first(where: {$0.id == account.id }) {
AccountDataHandler.shared.remove(accountData: dbAccount)
}
}
// Delete from local state.
self.accounts.remove(atOffsets: offsets)
// When we are deleting active user then we have to switch to sing in view.
if shouldClearApplicationState {
// We have to do this after animation of deleting row is ended.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
ApplicationSettingsHandler.shared.setAccountAsDefault(accountData: nil)
self.applicationState.clearApplicationState()
self.client.clearAccount()
}
2023-01-27 17:31:28 +01:00
}
}
2023-01-13 13:37:01 +01:00
}