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 SwiftUI
3@MainActor public struct DocsWorkspace: View {
4 @State private var model: DocsModel
5 @State private var query = ""
6 @State private var renaming = false
7 @FocusState private var titleFocused: Bool
8 private let newDocument: Bool
9 private let createDocument: (() -> Void)?
10 private let documentChanged: ((String, String) -> Void)?
11 @AppStorage("docs.view.paged") private var paged = true
12 /// The Share panel showing now (iPhone: the sheet's; Mac: the popover's).
13 @State private var sharePanel: DocsSharePanelModel?
14 #if os(macOS)
15 @State private var sharePopover = DocsSharePopover()
16 @State private var closer = DocsWindowCloser()
17 #endif
18 /// Delete…: the confirmation, and what to say when it is refused or fails.
19 @State private var confirmingDelete = false
20 @State private var deleteNotice: String?
21 @State private var exportRequest: String?
22 @Environment(\.openWindow) private var openWindow
23 @Environment(\.scenePhase) private var scenePhase
24 @Environment(\.locale) private var locale
25 @State private var jumping = false
26 @State private var countingWords = false
27 @State private var showingShortcuts = false
28 @State private var showingColophon = false
29 @State private var discarding = false
30 @State private var images = DocsImageStore()
31 @State private var column: NavigationSplitViewColumn = .sidebar
32 #if os(iOS)
33 /// iPhone (S3): the library is the stack's root and the document is pushed.
34 @State private var phonePath: [DocsPhoneRoute] = []
35 /// The iPhone document's large title and keyboard bar, one per window.
36 @State private var phoneChrome: DocsPhoneEditorChrome
37 /// The Format sheet (Aa), and Rename's alert.
38 @State private var formatting = false
39 /// A ••• action waiting for the Format sheet to go (two sheets cannot be
40 /// up at once: the second would be dropped).
41 @State private var afterFormatting: (() -> Void)?
42 /// The Format sheet is on screen (presented, not only asked for).
43 @State private var formatShown = false
44 @State private var renamingAlert = false
45 /// Why the last rename was refused, shown in the alert brought back.
46 @State private var renameRefusal: String?
47 @State private var renameText = ""
48 #endif
49 private let updateRecents: (([(String, String)]) -> Void)?
50 private let canSignOut: Bool
51 @Binding private var accountsRequested: Bool
52 @Binding private var signOutRequested: Bool
53 /// Oficina ID's words for the account controls: "Teams" and
54 /// "Sign out of <label>". nil keeps the server sign-in's own.
55 private let accountsLabel: String?
56 private let signOutLabel: String?
57 /// "Use another Oficina ID" in the account menu (Paul, 2026-11-19); nil
58 /// for a server account, and while it can't be asked.
59 private let useAnother: (() -> Void)?
60 @Binding private var createRequested: Bool
61 private let documentID: String?
62 private let openDocument: ((String, String) -> Void)?
63 @State private var zoom = 1.0
64 #if os(macOS)
65 /// The floating Format inspector, one state for the whole app (spec D1).
66 @AppStorage(DocsInspectorState.key) private var inspectorOpen = DocsInspectorState.defaultOpen
67 @Environment(\.layoutDirection) private var layoutDirection
68 #endif
69 /// The subtitle's team (spec D7): the account's team, or the server
70 /// account's name. nil says the state alone.
71 private let team: String?
72 private let signOut: () -> Void
73 private let accounts: (() -> Void)?
74 private let client: NativeHTTP
75 private let transport: (@MainActor () -> NativeTransport?)?
76 private let accountID: String?
77 /// Who "(you)" is in the Share panel: the account's label, when known.
78 private let accountLabel: String?
79 /// This window's document was deleted (Delete…): File ▸ Recent forgets it.
80 private let documentDeleted: ((String) -> Void)?
81 /// Why a sign-out asked from Settings was refused, said rather than swallowed.
82 @State private var signOutRefusal: DocsLeaveBlock?
83 /// `transport` supplies the account's current session to the model on every
84 /// request; without one the model keeps `client` for its whole lifetime.
85 public init(client: NativeHTTP, accountID: String? = nil, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), signOutRequested: Binding<Bool> = .constant(false), accountsLabel: String? = nil, signOutLabel: String? = nil, useAnother: (() -> Void)? = nil, openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil, team: String? = nil, connectivity: NativeConnectivity? = nil, accountLabel: String? = nil, documentDeleted: ((String) -> Void)? = nil) {
86 self.team = team; self.accountLabel = accountLabel; self.documentDeleted = documentDeleted
87 self._signOutRequested = signOutRequested; self.accountsLabel = accountsLabel; self.signOutLabel = signOutLabel; self.useAnother = useAnother
88 self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument
89 self.newDocument = newDocument; self.createDocument = createDocument; self.documentChanged = documentChanged
90 self.accountID = accountID
91 let offline = accountID.map { DocsOfflineAccount.account($0, origin: client.origin, fallback: client, transport: transport) }
92 let made = DocsModel(transport: transport ?? { client }, connectivity: connectivity, draft: newDocument, offlineAccount: offline)
93 _model = State(initialValue: made); self.signOut = signOut; self.accounts = accounts; self.client = client; self.transport = transport
94 #if os(iOS)
95 _phoneChrome = State(initialValue: DocsPhoneEditorChrome(model: made, team: team))
96 #endif
97 }
98 private var library: some View {
99 List {
100 ForEach(model.documents) { document in
101 Button { openFromLibrary(document.sqid) } label: {
102 HStack { DocumentThumbnail(data: document.thumbnail); Text(document.title); if document.shared == true { Image(systemName: "person.2") } }
103 }.buttonStyle(.plain)
104 }
105 }
106 .searchable(text: $query, prompt: Text("docs.list.search.label", bundle: DocsResources.bundle))
107 .onSubmit(of: .search) { Task { await model.load(query: query) } }
108 .navigationTitle(Text("native.docs", bundle: DocsResources.bundle))
109 .toolbar {
110 if let accounts {
111 ToolbarItem(placement: .navigation) {
112 DocsUnsavedGatedButton(model: model, action: accounts) {
113 Label(accountsLabel ?? docsMacString("Accounts"), systemImage: accountsLabel == nil ? "chevron.backward" : "person.crop.circle")
114 }
115 .accessibilityIdentifier("docs.accounts")
116 }
117 }
118
119 ToolbarItemGroup {
120 DocsJumpControls(presented: $jumping)
121 if model.canCreate { Button { beginDocument() } label: { Label { Text("docs.list.create.label", bundle: DocsResources.bundle) } icon: { Image(systemName: "plus") } }.accessibilityIdentifier("docs.create") }
122 DocsUnsavedGatedButton(model: model, action: { if !model.hasUnsavedChanges && !model.creatingDocument { signOut() } }) { signOutText }
123 #if os(iOS)
124 // The Colophon, beside Sign out: the iPhone app has no
125 // settings screen of its own. The Mac has it in the Help menu.
126 Button { showingColophon = true } label: { Label(DocsColophonView.title, systemImage: "info.circle") }
127 .accessibilityIdentifier("docs.colophon.open")
128 #endif
129 }
130 }
131 #if os(iOS)
132 .sheet(isPresented: $showingColophon) {
133 DocsColophonView { showingColophon = false }
134 }
135 #endif
136 }
137 public var body: some View {
138 #if DOCS_PROBES
139 let _ = DocsProbes.workspaceBodies += 1
140 #endif
141 documentActions(Group {
142 #if os(macOS)
143 if documentID != nil || newDocument { editor } else { home }
144 #else
145 if Self.phoneLayout {
146 // iPhone (S3, spec §3): a stack; iPad keeps today's split view
147 // until S5 (§5, the gate).
148 NavigationStack(path: $phonePath) {
149 library.navigationDestination(for: DocsPhoneRoute.self) { _ in phoneEditor }
150 }
151 } else {
152 NavigationSplitView(preferredCompactColumn: $column) { library } detail: { editor }
153 }
154 #endif
155 })
156 .safeAreaInset(edge: .top, spacing: 0) {
157 DocsOfflineBannerSlot(model: model, origin: client.origin)
158 }
159 .alert(signOutRefusal?.message ?? "", isPresented: Binding(get: { signOutRefusal != nil }, set: { if !$0 { signOutRefusal = nil } })) {
160 Button { signOutRefusal = nil } label: { Text("native.close", bundle: DocsResources.bundle) }
161 }
162 .onChange(of: model.documents.map { "\($0.sqid)\u{0}\($0.title)" }) {
163 if query.isEmpty { updateRecents?(model.documents.map { ($0.sqid, $0.title) }) }
164 }
165 .onChange(of: accountsRequested && !model.creatingDocument, initial: true) { _, ready in
166 if ready { accountsRequested = false; accounts?() }
167 }
168 // Settings' "Sign out" asks the home window, which holds the guard:
169 // nothing unsent, no draft being created, no document windows open.
170 .onChange(of: signOutRequested, initial: true) { _, requested in
171 guard requested, documentID == nil, !newDocument else { return }
172 signOutRequested = false
173 if !canSignOut { signOutRefusal = .openDocuments }
174 else if model.hasUnsavedChanges || model.creatingDocument { signOutRefusal = .sending }
175 else { signOut() }
176 }
177 .onChange(of: createRequested, initial: true) { _, requested in
178 if requested && documentID == nil { beginDocument(); createRequested = false }
179 }
180 .task {
181 // Here, not in init: see DocsOfflineAccount.account.
182 if accountID != nil, let transport { model.offlineAccount.resume(transport: transport) }
183 if newDocument { await model.newDraft() } else if let documentID { await model.open(documentID) } else { await model.load() } }
184 .onChange(of: model.renameInput) { _, value in if value == nil { renaming = false } }
185 .onChange(of: [model.detail?.sqid, model.detail?.title]) {
186 if !model.isDraft, let detail = model.detail { documentChanged?(detail.sqid, detail.title) }
187 }
188 .sheet(isPresented: $jumping) { DocsJumpSheet(model: model, client: liveClient, openElsewhere: jumpOpensWindows ? openDocument : nil) }
189 .onDisappear { Task { await model.stop() } }
190 .onChange(of: scenePhase) { _, phase in
191 #if os(iOS)
192 // No stream in the background: its heartbeat would keep the radio
193 // up, and a suspended app's connection only returns as an error.
194 if phase == .background { model.suspendLiveUpdates() }
195 if phase == .active { model.resumeLiveUpdates() }
196 #endif
197 if phase == .background { Task { await model.persistReplica() } }
198 if phase == .active { Task { try? await model.offlineAccount.activate() } }
199 }
200 #if os(macOS)
201 .background { DocsCloseGuard(hasUnsaved: { model.hasUnsavedChanges }, save: { await model.saveAll() }, discard: { await model.discardAll() }).frame(width: 0, height: 0) }
202 #endif
203 .onChange(of: model.detail?.sqid) {
204 guard model.detail != nil else { return }
205 column = .detail
206 #if os(iOS)
207 if Self.phoneLayout, phonePath.isEmpty { phonePath = [.document] }
208 #endif
209 }
210 .confirmationDialog(Text("native.discard.title", bundle: DocsResources.bundle), isPresented: $discarding, titleVisibility: .visible) {
211 Button(role: .destructive) { Task { await model.discardAll(); showLibrary() } } label: { Text("native.discard.action", bundle: DocsResources.bundle) }
212 Button(role: .cancel) {} label: { Text("native.close.pending.cancel", bundle: DocsResources.bundle) }
213 } message: {
214 Text("native.close.pending.detail", bundle: DocsResources.bundle)
215 }
216 }
217 /// Delete…'s confirmation and notices, the Share sheet, and lists
218 /// leaving a document another window deleted.
219 private func documentActions<Content: View>(_ content: Content) -> some View {
220 content
221 // Another window deleted a document: a list leaves it now, then reloads.
222 .onReceive(NotificationCenter.default.publisher(for: .docsDocumentDeleted)) { note in
223 guard documentID == nil, !newDocument, (note.userInfo?["origin"] as? URL) == client.origin,
224 let sqid = note.userInfo?["sqid"] as? String else { return }
225 model.forgetListed(sqid)
226 Task { await model.load(query: query) }
227 }
228 .confirmationDialog(Text(verbatim: deleteHeading), isPresented: $confirmingDelete, titleVisibility: .visible) {
229 Button(role: .destructive) { confirmDelete() } label: { Text("docs.delete.confirm", bundle: DocsResources.bundle) }
230 .accessibilityIdentifier("docs.delete.confirm")
231 Button(role: .cancel) {} label: { Text("docs.delete.cancel", bundle: DocsResources.bundle) }
232 } message: {
233 Text("docs.delete.body", bundle: DocsResources.bundle)
234 }
235 .alert(Text(LocalizedStringKey(deleteNotice ?? "native.delete.failed"), bundle: DocsResources.bundle),
236 isPresented: Binding(get: { deleteNotice != nil }, set: { if !$0 { deleteNotice = nil } })) {
237 Button { deleteNotice = nil } label: { Text("native.close", bundle: DocsResources.bundle) }
238 }
239 #if os(iOS)
240 .sheet(item: $sharePanel) { panel in
241 ScrollView { DocsSharePanel(model: panel, me: accountLabel, close: { sharePanel = nil }) }
242 .presentationDetents([.medium, .large])
243 // Not by swipe while the once-only URL shows (spec §1, Low 14).
244 .interactiveDismissDisabled(panel.blocksOutsideDismissal)
245 .task { await panel.load() }
246 .onDisappear { panel.closed() }
247 }
248 #endif
249 }
250 /// "Delete “<title>”?": the title replaced in the looked-up string.
251 private var deleteHeading: String {
252 DocsStrings(locale: locale)("docs.delete.heading").replacingOccurrences(of: "{title}", with: model.detail?.title ?? "")
253 }
254 /// The origin is offline: Share…, Delete… and Export wait (spec §6, Offline).
255 private var originOffline: Bool { model.connectivity.isOffline(client.origin) }
256 /// The client sharing, export, images and Jump use, resolved when they
257 /// use it: the account's current session (re-minted every 24 hours and
258 /// on a 401, and watched for both) when the window has a supplier, the
259 /// one it was opened with otherwise.
260 private var liveClient: NativeTransport { Self.liveClient(transport, fallback: client) }
261
262 static func liveClient(_ transport: (@MainActor () -> NativeTransport?)?, fallback: NativeTransport) -> NativeTransport {
263 transport?() ?? fallback
264 }
265
266 private var signOutText: Text {
267 if let signOutLabel { return Text(verbatim: signOutLabel) }
268 return Text("docs.signout.label", bundle: DocsResources.bundle)
269 }
270 private func beginDocument() {
271 #if os(macOS)
272 createDocument?()
273 #else
274 Task {
275 guard await model.saveAll() else { return }
276 await model.discardAll()
277 await model.newDraft()
278 }
279 #endif
280 }
281 /// The document's images, loaded for the sources its blocks hold; the
282 /// surface draws again only the blocks holding one that arrives.
283 private func loadImages() async {
284 let documentPath = "/d/" + (model.detail?.sqid ?? "")
285 let client = liveClient
286 let surface = model.surface
287 images.changed = { [weak images] _ in
288 surface.imagesChanged(images?.images(forDocumentPath: documentPath, client: client) ?? [:])
289 }
290 await images.load(sources: model.imageSources, client: client, documentPath: documentPath)
291 }
292 private func beginRename() {
293 // Only a writer gets an editable title (spec §1, rename).
294 guard model.documentAccess == .writable else { return }
295 model.renameInput = model.detail?.title ?? ""
296 renaming = true; titleFocused = true
297 }
298 /// Commits the title; false when the model refused it (too long, not
299 /// saved on the device, no longer writable), and the field stays open.
300 @discardableResult private func finishRename() -> Bool {
301 guard renaming else { return true }
302 if model.commitRename() { renaming = false; return true }
303 return false
304 }
305 #if os(iOS)
306 private var documentTitle: some View {
307 Group {
308 if renaming {
309 TextField(String(localized: "docs.list.create.placeholder", bundle: DocsResources.bundle), text: Binding(get: { model.renameInput ?? model.detail?.title ?? "" }, set: { model.renameInput = $0 }))
310 .accessibilityIdentifier("docs.document.title")
311 .textFieldStyle(.plain).frame(minWidth: 180, maxWidth: 480)
312 .focused($titleFocused).onSubmit { finishRename() }
313 .onChange(of: titleFocused) { _, focused in if !focused { finishRename() } }
314 #if os(macOS)
315 .onExitCommand { model.renameInput = nil; renaming = false }
316 #endif
317 } else {
318 Text(model.detail?.title ?? " ")
319 .lineLimit(1).frame(minHeight: 20)
320 .onTapGesture(count: 2) { if model.detail?.can_write == true { beginRename() } }
321 .contextMenu {
322 Button { beginRename() } label: { Text("docs.document.rename", bundle: DocsResources.bundle) }
323 .disabled(model.detail?.can_write != true)
324 .keyboardShortcut("r", modifiers: [.command, .shift])
325 }
326 .accessibilityAction(named: Text("docs.document.rename", bundle: DocsResources.bundle)) { beginRename() }
327 }
328 }
329 }
330 #endif
331 /// Back to the library: the split view's sidebar, the iPhone's root.
332 private func showLibrary() {
333 column = .sidebar
334 #if os(iOS)
335 closeFormatting()
336 phonePath = []
337 #endif
338 }
339 /// A library row: the document, pushed on iPhone (again, when it is the
340 /// one already open).
341 private func openFromLibrary(_ sqid: String) {
342 #if os(iOS)
343 if Self.phoneLayout, model.detail?.sqid == sqid, !model.isDraft { phonePath = [.document]; return }
344 #endif
345 Task { await model.open(sqid) }
346 }
347 /// On the Mac, a jump from a document or the home window opens or
348 /// focuses the result's own window instead of replacing this one.
349 private var jumpOpensWindows: Bool {
350 #if os(macOS)
351 true
352 #else
353 false
354 #endif
355 }
356 /// Share… (spec §1): flushes first, as before, then the panel: a
357 /// popover under Share… on the Mac, a sheet on the iPhone. Share… while
358 /// it is open does nothing; offline and for a draft it is not offered.
359 private func share() {
360 guard let detail = model.detail, detail.can_share, !model.isDraft, model.documentAccess != .unavailable, !originOffline else { return }
361 #if os(macOS)
362 guard !sharePopover.isShown else { return }
363 #else
364 guard sharePanel == nil else { return }
365 #endif
366 let transport = transport, client = client
367 Task {
368 await model.flush()
369 guard !model.hasUnsavedChanges, model.detail?.sqid == detail.sqid else { return }
370 let panel = DocsSharePanelModel(sqid: detail.sqid, title: model.detail?.title ?? detail.title,
371 transport: { Self.liveClient(transport, fallback: client) })
372 #if os(macOS)
373 sharePopover.present(panel, me: accountLabel)
374 #else
375 sharePanel = panel
376 #endif
377 }
378 }
379 /// Delete… (spec §1): sends what is waiting, refuses while anything is
380 /// still unsent, then asks.
381 private func requestDelete() {
382 Task {
383 await model.flush()
384 switch model.deleteBlock(offline: originOffline) {
385 case nil: confirmingDelete = true
386 case .unsent?: deleteNotice = "native.delete.unsent"
387 case .offline?, .notOwner?: break
388 }
389 }
390 }
391 private func confirmDelete() {
392 guard let sqid = model.detail?.sqid else { return }
393 let origin = client.origin
394 Task {
395 let result = await model.deleteDocument()
396 switch result?.outcome {
397 case .deleted?:
398 // Every list leaves it (the home window, the iPhone library)
399 // and File ▸ Recent forgets it. Its window closes, or the
400 // iPhone goes back to the library, only if it is still the
401 // document open: another may have been opened meanwhile.
402 NotificationCenter.default.post(name: .docsDocumentDeleted, object: nil, userInfo: ["origin": origin, "sqid": sqid])
403 documentDeleted?(sqid)
404 guard result?.wasOpen == true else { return }
405 #if os(macOS)
406 closer.close()
407 #else
408 showLibrary()
409 #endif
410 case .stillThere?, .unknown?:
411 deleteNotice = "native.delete.failed"
412 case nil:
413 if model.deleteBlock(offline: false) == .unsent { deleteNotice = "native.delete.unsent" }
414 }
415 }
416 }
417 #if os(macOS)
418 /// A writer's window shows the inspector when the app-wide state says
419 /// open; a reader's never does, and never writes the state (spec §1).
420 private var showsInspector: Bool { inspectorOpen && model.documentAccess == .writable }
421 #endif
422 /// The side the floating inspector covers, for the desk's centring: an
423 /// input of the text view's host, like Pages and zoom.
424 private var inspectorSide: DocsDeskLayout.Side? {
425 #if os(macOS)
426 showsInspector ? (layoutDirection == .rightToLeft ? .left : .right) : nil
427 #else
428 nil
429 #endif
430 }
431 private var editor: some View {
432 VStack(spacing: 0) {
433 #if os(iOS)
434 DocsPhoneStatusRows(model: model, discard: { discarding = true })
435 #endif
436 if model.loading { ProgressView() }
437 if model.showsDocument {
438 // The text view's host reads only the surface, Pages,
439 // zoom and the inspector's side (spec 2026-11-22 §7
440 // Design 9): the text reaches it through the surface,
441 // never through this body.
442 #if os(iOS)
443 EditorToolbar(model: model)
444 Divider()
445 #endif
446 DocumentEditorHost(surface: model.surface, paged: paged, zoom: zoom, inspector: inspectorSide)
447 .equatable()
448 .id(model.editorIdentity)
449 #if os(macOS)
450 .overlay(alignment: .topTrailing) {
451 if showsInspector {
452 DocsFormatInspector(model: model)
453 .padding(.top, DocsDeskLayout.inspectorInset)
454 .padding(.trailing, DocsDeskLayout.inspectorInset)
455 }
456 }
457 #endif
458 .task(id: ["/d/" + (model.detail?.sqid ?? "")] + model.imageSources) { await loadImages() }
459 // Open a document… (⌘K) from the text view's keys: the
460 // jump palette as a sheet over this window, on the Mac
461 // too (spec §1, menus).
462 .onChange(of: model.jumpRequests) { jumping = true }
463 } else {
464 ContentUnavailableView { Label { Text("native.open", bundle: DocsResources.bundle) } icon: { Image(systemName: "doc.text") } }
465 }
466 }.navigationTitle(model.detail?.title ?? "")
467 #if os(macOS)
468 // One title (spec §1): the window's title stays the document's,
469 // for the Window menu, tabs and VoiceOver, but the system does
470 // not draw it; Docs' title area does, with the subtitle.
471 .overlay(alignment: .top) { DocsDocumentCallouts(model: model, discard: { discarding = true }, inspectorShown: showsInspector, signIn: { openWindow(id: "home") }) }
472 .toolbar(removing: .title)
473 .toolbar {
474 ToolbarItem(placement: .navigation) {
475 DocsTitleArea(model: model, team: team, renaming: $renaming, beginRename: beginRename, finishRename: finishRename)
476 }
477 .sharedBackgroundVisibility(.hidden)
478 ToolbarSpacer(.flexible)
479 // Three items, so a narrow window moves them into the » menu
480 // one at a time: Share… first, then Format, then undo/redo.
481 ToolbarItem(placement: .primaryAction) { DocsHeaderControls(model: model, inspectorOpen: $inspectorOpen, part: .history, share: share) }
482 .sharedBackgroundVisibility(.hidden)
483 ToolbarItem(placement: .primaryAction) { DocsHeaderControls(model: model, inspectorOpen: $inspectorOpen, part: .format, share: share) }
484 .sharedBackgroundVisibility(.hidden)
485 ToolbarItem(placement: .primaryAction) {
486 DocsHeaderControls(model: model, inspectorOpen: $inspectorOpen, part: .share, share: share, origin: client.origin, sharePopover: sharePopover)
487 }
488 .sharedBackgroundVisibility(.hidden)
489 }
490 #else
491 .toolbar { ToolbarItem(placement: .principal) { documentTitle } }
492 .navigationBarTitleDisplayMode(.inline)
493 #endif
494 #if os(iOS)
495 .toolbar {
496 DocsJumpControls(presented: $jumping)
497 if let detail = model.detail, !model.isDraft {
498 Toggle(isOn: $paged) { Text("docs.editor.menu.view.paged", bundle: DocsResources.bundle) }
499 DocumentExportControls(client: liveClient, sqid: detail.sqid, title: detail.title) {
500 return await model.saveAll()
501 }.id(detail.sqid)
502 if model.showsDocument { DocsToolsControls(model: model) }
503 }
504 if model.detail?.can_share == true, !model.isDraft {
505 DocsPhoneShareButton(model: model, origin: client.origin, share: share)
506 DocsPhoneDeleteButton(model: model, origin: client.origin, delete: requestDelete)
507 }
508 }
509 #else
510 .background {
511 DocsShareFallback(popover: sharePopover).frame(maxWidth: .infinity, maxHeight: .infinity).allowsHitTesting(false).accessibilityHidden(true)
512 DocsWindowReader(closer: closer).frame(width: 0, height: 0)
513 if let detail = model.detail, !model.isDraft {
514 DocumentExportControls(client: liveClient, sqid: detail.sqid, title: detail.title, prepare: { await model.saveAll() }, request: $exportRequest)
515 .frame(width: 0, height: 0).hidden().accessibilityHidden(true)
516 }
517 }
518 .focusedSceneValue(\.docsJump, $jumping)
519 .focusedSceneValue(\.docsEditor, DocsEditorContext(model: model, rename: beginRename, client: liveClient, origin: client.origin, zoom: $zoom, paged: $paged, share: share, delete: requestDelete, exportRequest: $exportRequest, jumping: $jumping, wordCount: $countingWords, shortcuts: $showingShortcuts))
520 .sheet(isPresented: $countingWords) { DocsLiveWordCountSheet(model: model) { countingWords = false } }
521 .sheet(isPresented: $showingShortcuts) { DocsShortcutsSheet { showingShortcuts = false } }
522 #endif
523
524 }
525 #if os(macOS)
526 private var home: some View {
527 NavigationSplitView {
528 List { Label(docsMacString("Recent"), systemImage: "clock").listRowBackground(Color.accentColor.opacity(0.12)) }
529 .navigationSplitViewColumnWidth(min: 160, ideal: 190, max: 240)
530 } detail: {
531 ScrollView {
532 VStack(alignment: .leading, spacing: 24) {
533 Text(docsMacString("Recent documents")).font(.largeTitle.bold())
534 if let error = model.errorKey {
535 Text(LocalizedStringKey(error), bundle: DocsResources.bundle).foregroundStyle(.red)
536 Button(docsMacString("Retry")) { Task { await model.load(query: query) } }
537 }
538 LazyVGrid(columns: [GridItem(.adaptive(minimum: 180, maximum: 240))], spacing: 24) {
539 ForEach(model.documents) { document in
540 Button { openDocument?(document.sqid, document.title) } label: {
541 VStack(alignment: .leading, spacing: 10) {
542 DocumentThumbnail(data: document.thumbnail, width: 170, height: 220)
543 Text(document.title).font(.headline).lineLimit(2)
544 if document.shared == true { Label(docsMacString("Shared"), systemImage: "person.2").font(.caption) }
545 }.frame(maxWidth: .infinity, alignment: .leading).padding(12)
546 }.buttonStyle(.plain)
547 }
548 }
549 if model.listState == .loading { ProgressView().frame(maxWidth: .infinity) }
550 if model.listState == .loaded && model.documents.isEmpty && !query.isEmpty {
551 ContentUnavailableView { Text("docs.list.search.none.title", bundle: DocsResources.bundle) } description: { Text("docs.list.search.none.body", bundle: DocsResources.bundle) }
552 }
553 if model.listState == .loaded && model.documents.isEmpty && query.isEmpty {
554 ContentUnavailableView(docsMacString("No documents"), systemImage: "doc.text", description: Text(docsMacString("Create a document to get started.")))
555 }
556 }.padding(28)
557 }
558 .navigationTitle(docsMacString("Home"))
559 .searchable(text: $query, prompt: Text("docs.list.search.label", bundle: DocsResources.bundle))
560 .onSubmit(of: .search) { Task { await model.load(query: query) } }
561 .focusedSceneValue(\.docsJump, $jumping)
562 .focusedSceneValue(\.docsAccountActions, DocsAccountActions(accounts: accounts, signOut: signOut, canManage: !model.creatingDocument, canSignOut: canSignOut && !model.creatingDocument,
563 useAnother: useAnother, accountsLabel: accountsLabel, signOutLabel: signOutLabel))
564 .toolbar {
565 Button(docsMacString("New document"), systemImage: "plus") { beginDocument() }.disabled(!model.canCreate)
566 }
567 }
568 }
569 #endif
570
571}
572
573/// The offline banner and the lost-changes alert, reading the outbox
574/// summary in their own body: read in the workspace's, every key (an entry
575/// queued, then sent) evaluated the whole workspace again (S1b, step 0).
576private struct DocsOfflineBannerSlot: View {
577 let model: DocsModel
578 let origin: URL
579 var body: some View {
580 NativeOfflineBanner(connectivity: model.connectivity, origin: origin, summary: model.outboxSummary)
581 .alert(NativeSyncStrings.kit.unsentLost, isPresented: Binding(
582 get: { model.lostChangesNotice != nil },
583 set: { showing in if !showing { Task { await model.dismissLostChangesNotice() } } }
584 )) {
585 Button { Task { await model.dismissLostChangesNotice() } } label: {
586 Text("native.close", bundle: DocsResources.bundle)
587 }
588 }
589 }
590}
591
592#if os(iOS)
593/// The iPhone's sync status and error rows, reading the sync status in
594/// their own body: read in the workspace's, every key (pending, sending,
595/// saved) evaluated the whole workspace again (S1b, step 0).
596private struct DocsPhoneStatusRows: View {
597 let model: DocsModel
598 let discard: () -> Void
599 var body: some View {
600 NativeSyncStatusView(status: model.syncStatus)
601 if let key = model.errorKey {
602 HStack {
603 Text(LocalizedStringKey(key), bundle: DocsResources.bundle)
604 Button { Task { await model.retry() } } label: { Text("native.retry", bundle: DocsResources.bundle) }
605 if model.hasUnsavedChanges {
606 Button(role: .destructive) { discard() } label: { Text("native.discard.action", bundle: DocsResources.bundle) }
607 }
608 }.padding().accessibilityElement(children: .contain)
609 }
610 }
611}
612#endif
613
614#if os(iOS)
615/// Share… on the iPhone (until S3 moves it into •••), reading the origin's
616/// connectivity in its own body: offline it waits (spec §6, Offline).
617private struct DocsPhoneShareButton: View {
618 let model: DocsModel
619 let origin: URL
620 let share: () -> Void
621 var body: some View {
622 let offline = model.connectivity.isOffline(origin)
623 Button(action: share) { Label { Text("docs.share.title", bundle: DocsResources.bundle) } icon: { Image(systemName: "person.badge.plus") } }
624 .disabled(offline || model.documentAccess == .unavailable)
625 .accessibilityHint(offline ? Text("native.share.offline", bundle: DocsResources.bundle) : Text(verbatim: ""))
626 .accessibilityIdentifier("docs.share")
627 }
628}
629
630/// Delete… on the iPhone, for owners (until S3 moves it into •••).
631private struct DocsPhoneDeleteButton: View {
632 let model: DocsModel
633 let origin: URL
634 let delete: () -> Void
635 var body: some View {
636 let offline = model.connectivity.isOffline(origin)
637 Button(role: .destructive, action: delete) {
638 Label { Text("docs.editor.menu.file.delete", bundle: DocsResources.bundle) } icon: { Image(systemName: "trash") }
639 }
640 .disabled(offline || model.documentAccess == .unavailable)
641 .accessibilityIdentifier("docs.delete")
642 }
643}
644#endif
645
646extension Notification.Name {
647 /// A document was deleted from this device: userInfo "origin" (URL) and
648 /// "sqid" (String). Lists of that origin leave it and reload.
649 static let docsDocumentDeleted = Notification.Name("docs.document.deleted")
650}
651
652/// A button disabled while anything is unsent or a draft is being created
653/// (Accounts, Sign out), reading that in its own body: read in the
654/// workspace's, every key evaluated the whole workspace again (S1b, step 0).
655private struct DocsUnsavedGatedButton<Title: View>: View {
656 let model: DocsModel
657 let action: () -> Void
658 @ViewBuilder let title: () -> Title
659 var body: some View {
660 Button(action: action) { title() }.disabled(model.hasUnsavedChanges || model.creatingDocument)
661 }
662}
663
664#if os(iOS)
665/// The iPhone stack's one destination: the open document.
666enum DocsPhoneRoute: Hashable { case document }
667
668extension DocsWorkspace {
669 /// iPhone gets the S3 layout; iPad keeps today's until S5 (spec §5: the
670 /// gate). Tests may force either.
671 nonisolated(unsafe) static var phoneLayoutOverride: Bool?
672 static var phoneLayout: Bool { phoneLayoutOverride ?? (UIDevice.current.userInterfaceIdiom == .phone) }
673
674 /// The iPhone document (spec §3): back, the undo/redo pill, Aa and •••
675 /// in the bar; the large title hosted in the text view's own scroll
676 /// view, folding into the bar; the Format sheet at the medium detent;
677 /// the keyboard bar; Rename by alert. No strip, no toolbar items, no
678 /// sync row: the subtitle says what the row did.
679 var phoneEditor: some View {
680 Group {
681 if model.showsDocument {
682 DocumentEditorHost(surface: model.surface, paged: paged, zoom: 1, phone: phoneChrome)
683 .equatable()
684 .id(model.editorIdentity)
685 .ignoresSafeArea(.container, edges: .bottom)
686 .task(id: ["/d/" + (model.detail?.sqid ?? "")] + model.imageSources) { await loadImages() }
687 .onChange(of: model.jumpRequests) { jumping = true }
688 } else if model.loading || model.detail != nil {
689 ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)
690 } else {
691 ContentUnavailableView { Label { Text("native.open", bundle: DocsResources.bundle) } icon: { Image(systemName: "doc.text") } }
692 }
693 }
694 .background(Color(uiColor: .systemGroupedBackground))
695 .safeAreaInset(edge: .top, spacing: 0) {
696 DocsPhoneCallouts(model: model, discard: { discarding = true }, back: { showLibrary() })
697 }
698 .navigationTitle(model.detail?.title ?? "")
699 .navigationBarTitleDisplayMode(.inline)
700 .toolbar {
701 // Centred: while it shows, undo and redo are in ••• (the
702 // coordinator's ruling on #180), which leaves it the room.
703 ToolbarItem(placement: .principal) { DocsPhoneInlineTitle(model: model, team: team, state: phoneChrome.header) }
704 ToolbarItem(placement: .topBarTrailing) {
705 DocsPhoneDocumentControls(model: model, origin: client.origin, paged: $paged, header: phoneChrome.header, actions: phoneActions)
706 }
707 }
708 .sheet(isPresented: $formatting, onDismiss: {
709 let next = afterFormatting
710 afterFormatting = nil
711 next?()
712 }) {
713 DocsFormatSheet(model: model, close: { formatting = false })
714 .presentationDetents([.medium])
715 .presentationBackgroundInteraction(.enabled(upThrough: .medium))
716 .presentationDragIndicator(.visible)
717 // The text scrolls clear of the sheet, selection above it.
718 .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height in
719 model.surface.sheetCovers(height)
720 }
721 .onAppear { formatShown = true }
722 .onDisappear { formatShown = false; model.surface.sheetCovers(0) }
723 }
724 .onChange(of: formatting) { _, open in
725 // The keyboard goes and the selection stays: the text view keeps
726 // first responder with an empty input view (spec §3).
727 model.surface.suppressKeyboard(open)
728 phoneChrome.header.sheetOpen = open
729 }
730 .onAppear { phoneChrome.openFormat = { formatting = true } }
731 // The sheet goes with the document (Back, a swipe, Delete, Discard)
732 // and with the right to write.
733 .onDisappear { closeFormatting() }
734 .onChange(of: model.documentAccess) { _, access in if access != .writable { closeFormatting() } }
735 .alert(Text("docs.document.rename", bundle: DocsResources.bundle), isPresented: $renamingAlert) {
736 TextField(text: $renameText) { Text("docs.list.create.placeholder", bundle: DocsResources.bundle) }
737 .accessibilityIdentifier("docs.rename.field")
738 Button { commitPhoneRename() } label: { Text("docs.document.rename", bundle: DocsResources.bundle) }
739 .accessibilityIdentifier("docs.rename.confirm")
740 Button(role: .cancel) { renameRefusal = nil; model.renameInput = nil } label: { Text("native.close.pending.cancel", bundle: DocsResources.bundle) }
741 } message: {
742 // An alert's message is one Text, there or not: empty unless refused.
743 Text(verbatim: renameRefusal.map { String(localized: String.LocalizationValue($0), bundle: DocsResources.bundle) } ?? "")
744 }
745 .background {
746 if let detail = model.detail, !model.isDraft {
747 DocumentExportControls(client: liveClient, sqid: detail.sqid, title: detail.title, prepare: { await model.saveAll() }, request: $exportRequest)
748 .frame(width: 0, height: 0).hidden().accessibilityHidden(true)
749 }
750 }
751 .sheet(isPresented: $countingWords) { DocsLiveWordCountSheet(model: model) { countingWords = false } }
752 .sheet(isPresented: $showingShortcuts) { DocsShortcutsSheet { showingShortcuts = false } }
753 .sheet(isPresented: $showingColophon) { DocsColophonView { showingColophon = false } }
754 }
755
756 /// Rename from the alert. Refused (a title too long, the right to write
757 /// gone, the device unable to save), the alert comes back with the
758 /// title as typed and why (Fable on #180), as the Mac's field stays.
759 func commitPhoneRename() {
760 model.renameInput = renameText
761 if model.commitRename() { renameRefusal = nil; return }
762 let typed = renameText.trimmingCharacters(in: .whitespacesAndNewlines)
763 renameRefusal = typed.utf8.count > 1024 ? "native.rename.tooLong" : (model.errorKey ?? "docs.error.generic")
764 // Once the alert that was answered has gone: one presented during
765 // its dismissal is dropped.
766 let document = model.detail?.sqid
767 Task { @MainActor in
768 try? await Task.sleep(for: .milliseconds(500))
769 if renameRefusal != nil, model.detail?.sqid == document { renamingAlert = true }
770 }
771 }
772
773 /// The Format sheet closed, and what it changed undone at once: a view
774 /// that has gone runs no `onChange`, and a text view attached later
775 /// takes the surface's state (Fable on #180).
776 func closeFormatting() {
777 formatting = false
778 afterFormatting = nil
779 model.surface.suppressKeyboard(false)
780 model.surface.sheetCovers(0)
781 phoneChrome.header.sheetOpen = false
782 // A refused rename's alert waiting to come back stays with this
783 // document (Fable's delta review, F7).
784 renameRefusal = nil
785 renamingAlert = false
786 }
787
788 var phoneActions: DocsPhoneActions {
789 var actions = DocsPhoneActions()
790 // Each closes the Format sheet first, then runs.
791 func run(_ action: @escaping () -> Void) -> () -> Void {
792 {
793 // Asked for but never on screen, there is no dismissal to
794 // wait for (Fable's delta review, F8).
795 if formatting && formatShown { afterFormatting = action; formatting = false }
796 else { formatting = false; action() }
797 }
798 }
799 actions.share = run { share() }
800 actions.rename = run {
801 guard model.documentAccess == .writable else { return }
802 renameText = model.detail?.title ?? ""
803 renameRefusal = nil
804 renamingAlert = true
805 }
806 actions.export = { kind in run { exportRequest = kind }() }
807 actions.wordCount = run { countingWords = true }
808 actions.openDocument = run { jumping = true }
809 actions.shortcuts = run { showingShortcuts = true }
810 actions.colophon = run { showingColophon = true }
811 actions.delete = run { requestDelete() }
812 actions.format = { formatting = true }
813 return actions
814 }
815}
816#endif
817