oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1import RastrilloApple
2import DocsKit
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 (spec 2026-11-14-oficina-id-native, slice A,
9/// and Paul's straight-in ruling of 2026-11-19): with one Oficina ID on the
10/// device Docs opens its team with no screen at all; otherwise the kit's
11/// onboarding until its model is signed in to a team, then that team's
12/// workspace. "Other ways to sign in…" is the server address and browser
13/// approval that came before, kept for self-hosted servers and local
14/// accounts; someone already signed in that way keeps those accounts until an
15/// Oficina ID replaces them (`DocsSignInRoute`), and nothing goes straight in
16/// while they do.
17///
18/// The body only reads: every change (start, route, suspension, the
19/// replace guard) happens in `.task`, `.onChange` or a button, never while
20/// building a view (84d1008, WorkspaceInitTests, SignedInLaunchTests).
21struct DocsAccountWindow: View {
22 @ObservedObject private var oficina: DocsOficinaSession
23 @ObservedObject private var model: OficinaIDModel
24 /// Why a sign-out or "Use another" was refused: said, not swallowed.
25 @State private var leaveRefusal: DocsLeaveBlock?
26 @StateObject private var connection = NativeConnection(defaultServer: "https://docs.oficina.works")
27 @AppStorage(DocsSignInRoute.key) private var storedRoute = ""
28 @State private var pickingTeam = false
29 @Environment(\.scenePhase) private var scenePhase
30 #if os(macOS)
31 @Bindable var windows: DocsWindows
32 @Environment(\.openWindow) private var openWindow
33 #endif
34
35 #if os(macOS)
36 init(oficina: DocsOficinaSession, windows: DocsWindows) {
37 _oficina = ObservedObject(wrappedValue: oficina); _model = ObservedObject(wrappedValue: oficina.model); _windows = Bindable(windows)
38 }
39 #else
40 init(oficina: DocsOficinaSession) { _oficina = ObservedObject(wrappedValue: oficina); _model = ObservedObject(wrappedValue: oficina.model) }
41 #endif
42
43 private var route: DocsSignInRoute {
44 DocsSignInRoute.resolve(stored: storedRoute, hasServerAccounts: !connection.accounts.isEmpty)
45 }
46
47 private func transport(for account: String?) -> @MainActor () -> NativeTransport? {
48 let connection = connection
49 return DocsAccountTransport.supplier(account: account,
50 active: { [weak connection] in connection?.activeAccountID },
51 client: { [weak connection] in connection?.client })
52 }
53
54 var body: some View {
55 Group {
56 switch route {
57 case .oficinaID:
58 // The mounted team stays while Oficina ID can't re-mint it (§11), with
59 // the line saying so over it, rather than unmounting an open editor.
60 if let state = oficina.mounted {
61 oficinaWorkspace(state)
62 .safeAreaInset(edge: .top, spacing: 0) { oficinaBanner }
63 // The account menu's "Use another Oficina ID" asks here; the
64 // onboarding carries its own for every other step.
65 .oficinaReplaceConfirmation(model)
66 } else {
67 OficinaOnboardingView(model: model, otherWays: { storedRoute = DocsSignInRoute.server.rawValue })
68 }
69 case .server:
70 if let client = connection.client { serverWorkspace(client) }
71 else { DocsOtherWaysView(connection: connection) { storedRoute = DocsSignInRoute.oficinaID.rawValue } }
72 }
73 }
74 .onOpenURL(perform: connection.handleOpenURL)
75 .task { await oficina.start(serverRoute: route == .server) }
76 // A sign-in with Oficina ID replaces the other ways for good (Appendix C).
77 // Only one made here: going straight in at launch (another app's
78 // identity, or last run's) leaves the route someone chose alone.
79 .onChange(of: oficina.signIns) { _, _ in storedRoute = DocsSignInRoute.oficinaID.rawValue }
80 // Straight in is suspended exactly while Docs' own sign-in is the route,
81 // however the route changes: chosen, or flipped by the last server
82 // account signing out (rule 0). Signed in, the session is undisturbed.
83 .onChange(of: route) { _, value in Task { await oficina.routeChanged(to: value) } }
84 // "Use another" signs the identity out on every app. The menu checks
85 // Docs' guards before the kit asks (`useAnother`); they are checked
86 // again however the confirmation appeared: never over an outage (no
87 // dialog to ask with on the mounted workspace), never with a document
88 // window of the identity open, never with changes unsent.
89 .onChange(of: model.confirmingReplace) { _, confirming in
90 guard confirming, let identity = model.identity?.id else { return }
91 if oficina.mounted != nil, !signedIn { model.cancelReplace(); return }
92 if openDocuments(of: identity) { model.cancelReplace(); leaveRefusal = .openDocuments; return }
93 Task {
94 if let block = await DocsLeaveBlock.check(identity: identity, openDocuments: openDocuments(of: identity)) {
95 model.cancelReplace(); leaveRefusal = block
96 }
97 }
98 }
99 // And while it asks: a document window of the identity opened from
100 // File ▸ Recent or ⌘N withdraws the question, as confirming would sign
101 // the identity out under it (#130, finding 2).
102 .onChange(of: replaceUnderOpenDocument) { _, open in
103 guard open else { return }
104 model.cancelReplace(); leaveRefusal = .openDocuments
105 }
106 .alert(leaveRefusal?.message ?? "", isPresented: Binding(get: { leaveRefusal != nil }, set: { if !$0 { leaveRefusal = nil } })) {
107 Button(OficinaIDText.text("cancel"), role: .cancel) { leaveRefusal = nil }
108 }
109 .onChange(of: scenePhase) { _, phase in
110 if phase == .active { Task { await oficina.renewIfNeeded() } }
111 }
112 #if os(macOS)
113 .onChange(of: windows.accountsRequested, initial: true) { _, requested in
114 if requested && currentClient == nil { windows.accountsRequested = false }
115 }
116 .onChange(of: windows.signOutRequested, initial: true) { _, requested in
117 if requested && currentClient == nil { windows.signOutRequested = false }
118 }
119 .focusedSceneValue(\.docsWindowAccount, currentAccount)
120 // An identity gone (signed out here or in another app, or replaced by
121 // "Use another") takes its closed windows' recents and transports with
122 // it: their sessions are gone.
123 .onChange(of: model.identity?.id) { old, new in
124 guard let old, old != new else { return }
125 windows.entries.removeAll { DocsOficinaSession.account($0.account, belongsTo: old) && !$0.isOpen }
126 let open = Set(windows.entries.filter(\.isOpen).map(\.account))
127 windows.transports = windows.transports.filter { !DocsOficinaSession.account($0.key, belongsTo: old) || open.contains($0.key) }
128 }
129 .onChange(of: currentAccount, initial: true) { _, value in windows.activeAccount = value }
130 .onChange(of: settingsAccount, initial: true) { _, value in windows.settingsAccount = value }
131 .onChange(of: route == .oficinaID ? oficina.mounted?.identity.id : nil, initial: true) { _, value in windows.settingsIdentity = value }
132 #endif
133 }
134
135 private var currentAccount: String? {
136 switch route {
137 case .oficinaID: return oficina.mounted.map(DocsOficinaSession.accountID)
138 case .server: return connection.activeAccountID
139 }
140 }
141
142 private var currentClient: NativeHTTP? {
143 switch route {
144 case .oficinaID: return oficina.mounted.flatMap { oficina.client(for: DocsOficinaSession.accountID($0)) }
145 case .server: return connection.client
146 }
147 }
148
149 // MARK: Oficina ID
150
151 @ViewBuilder private func oficinaWorkspace(_ state: OficinaSignedIn) -> some View {
152 let account = DocsOficinaSession.accountID(state)
153 let client = oficina.client(for: account) ?? state.client()
154 #if os(macOS)
155 let canLeave = !openDocuments(of: state.identity.id)
156 DocsWorkspace(client: client, accountID: account, transport: oficina.transport(for: account), accounts: { pickingTeam = true }, signOut: {
157 signOutOficinaID(state)
158 }, createDocument: {
159 guard currentAccount == account else { return }
160 let id = windows.reserveDraft(account: account, client: client)
161 openWindow(id: "document", value: id)
162 }, canSignOut: canLeave, createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested,
163 signOutRequested: $windows.signOutRequested, accountsLabel: teamsLabel, signOutLabel: OficinaIDText.text("signOut", state.identity.label),
164 useAnother: signedIn ? { useAnother(state) } : nil,
165 openDocument: { document, title in
166 guard currentAccount == account else { return }
167 let id = windows.reserve(account: account, document: document, title: title, client: client)
168 openWindow(id: "document", value: id)
169 }, updateRecents: { documents in
170 guard currentAccount == account else { return }
171 windows.updateRecents(documents, account: account, client: client)
172 })
173 .id(account)
174 .onAppear {
175 windows.transports[account] = oficina.transport(for: account)
176 windows.teamNames[account] = state.team.name
177 }
178 .safeAreaInset(edge: .bottom, spacing: 0) { passkeyNudge }
179 .sheet(isPresented: $pickingTeam) { teamPicker(state) }
180 #else
181 DocsWorkspace(client: client, accountID: account, transport: oficina.transport(for: account), accounts: { pickingTeam = true },
182 signOut: { signOutOficinaID(state) }, accountsLabel: teamsLabel,
183 signOutLabel: OficinaIDText.text("signOut", state.identity.label), accountLabel: state.identity.label)
184 .id(account)
185 .safeAreaInset(edge: .bottom, spacing: 0) { passkeyNudge }
186 .sheet(isPresented: $pickingTeam) { teamPicker(state) }
187 #endif
188 }
189
190 private var teamsLabel: String { DocsOficinaSession.teamsTitle }
191
192 /// Whether the model holds a live team session: "Use another Oficina ID"
193 /// is offered only then, as over an outage there is no dialog to ask with.
194 private var signedIn: Bool {
195 if case .signedIn = model.step { return true }
196 return false
197 }
198
199 /// "Use another Oficina ID" from the account menu. Slice A replaces the
200 /// identity, so the kit asks (`oficinaReplaceConfirmation`), but only
201 /// after the sign-out guard: refused, and said, with a document window of
202 /// the identity open or its changes unsent (`requestUseAnother`).
203 private func useAnother(_ state: OficinaSignedIn) {
204 let identity = state.identity.id
205 if openDocuments(of: identity) { leaveRefusal = .openDocuments; return }
206 Task {
207 if let block = await oficina.requestUseAnother(identity: identity, openDocuments: { openDocuments(of: identity) }) {
208 leaveRefusal = block
209 }
210 }
211 }
212
213 /// The kit is asking to replace the identity while one of its document
214 /// windows is open. Only read here; acted on in `.onChange`.
215 private var replaceUnderOpenDocument: Bool {
216 guard model.confirmingReplace, let identity = model.identity?.id else { return false }
217 return openDocuments(of: identity)
218 }
219
220 @ViewBuilder private var passkeyNudge: some View {
221 if model.offerPasskey { OficinaPasskeyNudge(model: model).padding(12) }
222 }
223
224 /// Whether a document window of any of `identity`'s teams is open (Mac).
225 private func openDocuments(of identity: String) -> Bool {
226 #if os(macOS)
227 return windows.hasOpenDocuments(identity: identity)
228 #else
229 return false
230 #endif
231 }
232
233 /// Over a mounted workspace: Oficina ID can't mint this team a session
234 /// right now (§11), or a team switch failed. Try again, or carry on with
235 /// what is open; nothing is unmounted.
236 @ViewBuilder private var oficinaBanner: some View {
237 if case .unavailable = model.step {
238 HStack(spacing: 12) {
239 OficinaErrorLine(OficinaIDText.text("unavailable.title") + ". " + OficinaIDText.text("unavailable.body"))
240 Spacer(minLength: 0)
241 Button(OficinaIDText.text("unavailable.retry")) { Task { await model.retry() } }.disabled(model.busy)
242 .accessibilityIdentifier("docs.oficinaid.retry")
243 }
244 .padding(.horizontal, 16).padding(.vertical, 8).background(OficinaPalette.negativeSoft)
245 } else if let error = model.error {
246 OficinaErrorLine(error).padding(.horizontal, 16).padding(.vertical, 8)
247 .frame(maxWidth: .infinity, alignment: .leading).background(OficinaPalette.negativeSoft)
248 }
249 }
250
251 private func teamPicker(_ state: OficinaSignedIn) -> some View {
252 DocsTeamPicker(model: model, current: state, leaveCheck: {
253 await DocsLeaveBlock.check(identity: state.identity.id, openDocuments: openDocuments(of: state.identity.id))
254 }, refresh: { await oficina.pickerOpened() }, otherWays: {
255 pickingTeam = false
256 model.suspendStraightIn()
257 storedRoute = DocsSignInRoute.server.rawValue
258 }, useAnother: signedIn ? {
259 pickingTeam = false
260 useAnother(state)
261 } : nil, signOut: {
262 pickingTeam = false
263 signOutOficinaID(state)
264 }, done: { pickingTeam = false })
265 }
266
267 /// "Sign out of <label>": every team of the identity, on every Oficina app
268 /// on this device (spec §10), after Docs' own guard: the workspace refuses
269 /// while anything is unsent, and the Mac while a document window of any
270 /// of the identity's teams is open.
271 private func signOutOficinaID(_ state: OficinaSignedIn) {
272 let identity = state.identity.id
273 Task {
274 // Identity-wide: every team's outbox, those a crash left on disk too.
275 if let block = await DocsLeaveBlock.check(identity: identity, openDocuments: openDocuments(of: identity)) {
276 leaveRefusal = block; return
277 }
278 guard model.identity?.id == identity else { return }
279 #if os(macOS)
280 windows.entries.removeAll { DocsOficinaSession.account($0.account, belongsTo: identity) }
281 windows.transports = windows.transports.filter { !DocsOficinaSession.account($0.key, belongsTo: identity) }
282 #endif
283 model.signOut()
284 }
285 }
286
287 // MARK: Other ways (server address)
288
289 @ViewBuilder private func serverWorkspace(_ client: NativeHTTP) -> some View {
290 #if os(macOS)
291 if let account = connection.activeAccountID {
292 DocsWorkspace(client: client, accountID: account, transport: transport(for: account), accounts: connection.showAccounts, signOut: {
293 guard connection.activeAccountID == account, windows.canSignOut(account) else { return }
294 windows.entries.removeAll { $0.account == account }
295 connection.signOut()
296 }, createDocument: {
297 guard connection.activeAccountID == account else { return }
298 let id = windows.reserveDraft(account: account, client: client)
299 openWindow(id: "document", value: id)
300 }, canSignOut: windows.canSignOut(account), createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested,
301 signOutRequested: $windows.signOutRequested, openDocument: { document, title in
302 guard connection.activeAccountID == account else { return }
303 let id = windows.reserve(account: account, document: document, title: title, client: client)
304 openWindow(id: "document", value: id)
305 }, updateRecents: { documents in
306 guard connection.activeAccountID == account else { return }
307 windows.updateRecents(documents, account: account, client: client)
308 })
309 .id(account)
310 .onAppear { windows.teamNames[account] = connection.accounts.first { $0.id == account }?.name }
311 .onChange(of: connection.accounts) { _, accounts in windows.teamNames[account] = accounts.first { $0.id == account }?.name }
312 }
313 #else
314 DocsWorkspace(client: client, accountID: connection.activeAccountID, transport: transport(for: connection.activeAccountID), accounts: connection.showAccounts, signOut: connection.signOut)
315 .id(connection.activeAccountID)
316 #endif
317 }
318
319 #if os(macOS)
320 private var settingsAccount: DocsSettingsView.Account {
321 switch route {
322 case .oficinaID:
323 guard let state = oficina.mounted else { return .none }
324 return .oficinaID(identity: state.identity.label, team: state.team.name, teamLabel: state.team.label)
325 case .server:
326 guard let client = connection.client else { return .none }
327 let name = connection.accounts.first { $0.id == connection.activeAccountID }?.name ?? ""
328 return .server(name: name, host: client.origin.host ?? client.origin.absoluteString)
329 }
330 }
331 #endif
332}
333