import RastrilloApple import DocsKit import SwiftUI /// Each window owns its navigation and model lifetime. Switching an account in /// one window must never discard another window's unconfirmed edits. struct DocsAccountWindow: View { @StateObject private var connection = NativeConnection(defaultServer: "https://docs.oficina.works") #if os(macOS) @Bindable var windows: DocsWindows @Environment(\.openWindow) private var openWindow #endif private func transport(for account: String?) -> @MainActor () -> NativeTransport? { let connection = connection return DocsAccountTransport.supplier(account: account, active: { [weak connection] in connection?.activeAccountID }, client: { [weak connection] in connection?.client }) } var body: some View { Group { if let client = connection.client { #if os(macOS) if let account = connection.activeAccountID { DocsWorkspace(client: client, accountID: account, transport: transport(for: account), accounts: connection.showAccounts, signOut: { guard connection.activeAccountID == account, windows.canSignOut(account) else { return } windows.entries.removeAll { $0.account == account } connection.signOut() }, createDocument: { guard connection.activeAccountID == account else { return } let id = windows.reserveDraft(account: account, client: client) openWindow(id: "document", value: id) }, canSignOut: windows.canSignOut(account), createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested, openDocument: { document, title in guard connection.activeAccountID == account else { return } let id = windows.reserve(account: account, document: document, title: title, client: client) openWindow(id: "document", value: id) }, updateRecents: { documents in guard connection.activeAccountID == account else { return } windows.updateRecents(documents, account: account, client: client) }) .id(account) } #else DocsWorkspace(client: client, accountID: connection.activeAccountID, transport: transport(for: connection.activeAccountID), accounts: connection.showAccounts, signOut: connection.signOut) .id(connection.activeAccountID) #endif } else { NativeAccountsView("Oficina Docs", systemImage: "doc.text", connection: connection) } }.onOpenURL(perform: connection.handleOpenURL) #if os(macOS) .onChange(of: windows.accountsRequested, initial: true) { _, requested in if requested && connection.client == nil { windows.accountsRequested = false } } .focusedSceneValue(\.docsWindowAccount, connection.activeAccountID) .onChange(of: connection.activeAccountID, initial: true) { _, value in windows.activeAccount = value } #endif } }