oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1import RastrilloApple
2import SheetsKit
3import SwiftUI
4
5/// Each window owns its navigation and model lifetime. Switching an account in
6/// one window must never discard another window's unconfirmed edits.
7///
8/// Sign-in is Oficina ID first (Home spec 2026-11-14-oficina-id-native, slice
9/// A, and Paul's straight-in ruling of 2026-11-19): with one Oficina ID on the
10/// device Sheets opens its team with no screen at all; otherwise the kit's
11/// onboarding until its model is signed in, then that team's workspace. "Other
12/// ways to sign in…" is the server address and browser approval that came
13/// before, kept for self-hosted servers and local accounts; someone already
14/// signed in that way keeps those accounts until an Oficina ID replaces them
15/// (`SheetsSignInRoute`), and nothing goes straight in while they do.
16///
17/// The body only reads: every change (start, route, suspension) happens in
18/// `.task` or `.onChange`, never while building a view (docs 84d1008).
19struct SheetsAccountWindow: View {
20 @ObservedObject private var oficina: SheetsOficinaSession
21 @ObservedObject private var model: OficinaIDModel
22 @StateObject private var connection = NativeConnection(defaultServer: "https://sheets.oficina.works")
23 @AppStorage(SheetsSignInRoute.key) private var storedRoute = ""
24 @State private var pickingTeam = false
25 @Environment(\.scenePhase) private var scenePhase
26 #if os(macOS)
27 @Bindable var windows: SheetsWindows
28 @Environment(\.openWindow) private var openWindow
29 #endif
30
31 #if os(macOS)
32 init(oficina: SheetsOficinaSession, windows: SheetsWindows) {
33 _oficina = ObservedObject(wrappedValue: oficina); _model = ObservedObject(wrappedValue: oficina.model); _windows = Bindable(windows)
34 }
35 #else
36 init(oficina: SheetsOficinaSession) {
37 _oficina = ObservedObject(wrappedValue: oficina); _model = ObservedObject(wrappedValue: oficina.model)
38 }
39 #endif
40
41 private var route: SheetsSignInRoute {
42 SheetsSignInRoute.resolve(stored: storedRoute, hasServerAccounts: !connection.accounts.isEmpty)
43 }
44
45 var body: some View {
46 Group {
47 switch route {
48 case .oficinaID:
49 if let state = oficina.mounted {
50 oficinaWorkspace(state)
51 .safeAreaInset(edge: .top, spacing: 0) { oficinaBanner }
52 .oficinaReplaceConfirmation(model)
53 } else {
54 OficinaOnboardingView(model: model, otherWays: { storedRoute = SheetsSignInRoute.server.rawValue })
55 }
56 case .server:
57 if let client = connection.client { serverWorkspace(client) }
58 else {
59 SheetsOtherWaysView(connection: connection) { storedRoute = SheetsSignInRoute.oficinaID.rawValue }
60 }
61 }
62 }
63 .onOpenURL(perform: connection.handleOpenURL)
64 .task { await oficina.start(serverRoute: route == .server) }
65 // A sign-in made here chooses Oficina ID for good (Appendix C); a launch
66 // going straight in leaves the route someone chose alone.
67 .onChange(of: oficina.signIns) { _, _ in storedRoute = SheetsSignInRoute.oficinaID.rawValue }
68 // Straight in is suspended exactly while the app's own sign-in is the
69 // route, however the route changes: chosen, or flipped by the last
70 // server account signing out (rule 0).
71 .onChange(of: route) { _, value in Task { await oficina.routeChanged(to: value) } }
72 // "Use another" re-checks the document guard when it asks, as signing
73 // out does, and is never left asking over an outage.
74 .onChange(of: model.confirmingReplace) { _, confirming in
75 guard confirming else { return }
76 let signedIn: Bool
77 if case .signedIn = model.step { signedIn = true } else { signedIn = false }
78 if oficina.mounted != nil, !signedIn || openDocuments(of: model.identity?.id ?? "") { model.cancelReplace() }
79 }
80 .onChange(of: scenePhase) { _, phase in
81 if phase == .active { Task { await oficina.renewIfNeeded() } }
82 }
83 #if os(macOS)
84 .onChange(of: windows.accountsRequested, initial: true) { _, requested in
85 if requested && currentAccount == nil { windows.accountsRequested = false }
86 }
87 .focusedSceneValue(\.sheetsWindowAccount, currentAccount)
88 // An identity gone (signed out here or elsewhere, or replaced by "Use
89 // another") takes its recents with it: their transports answer nothing.
90 .onChange(of: model.identity?.id) { old, new in
91 guard let old, old != new else { return }
92 windows.entries.removeAll { SheetsOficinaSession.account($0.account, belongsTo: old) && !$0.isOpen }
93 }
94 .onChange(of: currentAccount, initial: true) { _, value in windows.activeAccount = value }
95 #endif
96 .tint(.green)
97 #if os(macOS)
98 .frame(minWidth: 760, minHeight: 600)
99 #endif
100 }
101
102 private var currentAccount: String? {
103 switch route {
104 case .oficinaID: return oficina.mounted.map(SheetsOficinaSession.accountID)
105 case .server: return connection.activeAccountID
106 }
107 }
108
109 // MARK: Oficina ID
110
111 @ViewBuilder private func oficinaWorkspace(_ state: OficinaSignedIn) -> some View {
112 let account = SheetsOficinaSession.accountID(state)
113 let client = oficina.transport(for: account, origin: state.origin)
114 let canLeave = !openDocuments(of: state.identity.id)
115 #if os(macOS)
116 SheetsWorkspace(client: client, accounts: { pickingTeam = true }, signOut: { signOutOficinaID(state) },
117 canSignOut: canLeave, createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested,
118 openDocument: { document, title in
119 guard currentAccount == account else { return }
120 let id = windows.reserve(account: account, document: document, title: title, client: client)
121 openWindow(id: "document", value: id)
122 }, updateRecents: { documents in
123 guard currentAccount == account else { return }
124 windows.updateRecents(documents, account: account, client: client)
125 }, useAnother: canUseAnother ? { useAnother(state) } : nil, accountsLabel: sheetsMacString("Teams"),
126 signOutLabel: OficinaIDText.text("signOut", state.identity.label))
127 .id(account)
128 .safeAreaInset(edge: .bottom, spacing: 0) { passkeyNudge }
129 .sheet(isPresented: $pickingTeam) { teamPicker(state, canLeave: canLeave) }
130 #else
131 SheetsWorkspace(client: client, accounts: { pickingTeam = true }, signOut: { signOutOficinaID(state) },
132 useAnother: canUseAnother ? { useAnother(state) } : nil, accountsLabel: sheetsMacString("Teams"),
133 signOutLabel: OficinaIDText.text("signOut", state.identity.label))
134 .id(account)
135 .safeAreaInset(edge: .bottom, spacing: 0) { passkeyNudge }
136 .sheet(isPresented: $pickingTeam) { teamPicker(state, canLeave: canLeave) }
137 #endif
138 }
139
140 @ViewBuilder private var passkeyNudge: some View {
141 if model.offerPasskey { OficinaPasskeyNudge(model: model).padding(12) }
142 }
143
144 /// Over the mounted workspace: Oficina ID can't mint this team a new
145 /// session right now (§11), so the open team stays, with Try again. A
146 /// switch to another team that fails the same way unmounts this one and
147 /// shows the kit's "Can't reach Oficina ID" (Try again, Other ways), as
148 /// Docs does.
149 @ViewBuilder private var oficinaBanner: some View {
150 if case .unavailable = model.step {
151 HStack(spacing: 12) {
152 OficinaErrorLine(OficinaIDText.text("unavailable.title") + ". " + OficinaIDText.text("unavailable.body"))
153 Spacer(minLength: 0)
154 Button(OficinaIDText.text("unavailable.retry")) { Task { await model.retry() } }.disabled(model.busy)
155 .accessibilityIdentifier("sheets.oficinaid.retry")
156 }
157 .padding(.horizontal, 16).padding(.vertical, 8).background(OficinaPalette.negativeSoft)
158 } else if let error = model.error {
159 OficinaErrorLine(error).padding(.horizontal, 16).padding(.vertical, 8)
160 .frame(maxWidth: .infinity, alignment: .leading).background(OficinaPalette.negativeSoft)
161 }
162 }
163
164 private func teamPicker(_ state: OficinaSignedIn, canLeave: Bool) -> some View {
165 SheetsTeamPicker(model: model, current: state, canLeave: canLeave, refresh: { await oficina.pickerOpened() },
166 otherWays: {
167 model.suspendStraightIn()
168 storedRoute = SheetsSignInRoute.server.rawValue
169 }, useAnother: { useAnother(state) }, signOut: { signOutOficinaID(state) }, done: { pickingTeam = false })
170 }
171
172 /// Whether a document window of any of `identity`'s teams is open (Mac).
173 private func openDocuments(of identity: String) -> Bool {
174 #if os(macOS)
175 return windows.hasOpenDocuments(identity: identity)
176 #else
177 return false
178 #endif
179 }
180
181 /// "Use another Oficina ID" is offered only while signed in: over an
182 /// outage there is no dialog to ask with.
183 private var canUseAnother: Bool {
184 if case .signedIn = model.step { return true }
185 return false
186 }
187
188 /// "Use another Oficina ID" from the account menu: slice A replaces the
189 /// identity, so the kit asks first (`oficinaReplaceConfirmation` above),
190 /// and the same guard as signing out applies.
191 private func useAnother(_ state: OficinaSignedIn) {
192 oficina.useAnother(identity: state.identity.id, canLeave: !openDocuments(of: state.identity.id))
193 }
194
195 /// "Sign out of <label>": every team of the identity, on every Oficina app
196 /// on this device (spec §10), refused while one of its document windows
197 /// is open (the menu disables it then too).
198 private func signOutOficinaID(_ state: OficinaSignedIn) {
199 let identity = state.identity.id
200 guard oficina.signOut(identity: identity, canLeave: !openDocuments(of: identity)) else { return }
201 #if os(macOS)
202 windows.entries.removeAll { SheetsOficinaSession.account($0.account, belongsTo: identity) }
203 #endif
204 }
205
206 // MARK: Other ways (server address)
207
208 @ViewBuilder private func serverWorkspace(_ client: NativeHTTP) -> some View {
209 #if os(macOS)
210 if let account = connection.activeAccountID {
211 SheetsWorkspace(client: client, accounts: connection.showAccounts, signOut: {
212 guard connection.activeAccountID == account, windows.canSignOut(account) else { return }
213 windows.entries.removeAll { $0.account == account }
214 connection.signOut()
215 }, canSignOut: windows.canSignOut(account), createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested, openDocument: { document, title in
216 guard connection.activeAccountID == account else { return }
217 let id = windows.reserve(account: account, document: document, title: title, client: client)
218 openWindow(id: "document", value: id)
219 }, updateRecents: { documents in
220 guard connection.activeAccountID == account else { return }
221 windows.updateRecents(documents, account: account, client: client)
222 })
223 .id(account)
224 }
225 #else
226 SheetsWorkspace(client: client, accounts: connection.showAccounts, signOut: connection.signOut)
227 .id(connection.activeAccountID)
228 #endif
229 }
230}
231