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 SwiftUI
3
4@MainActor public struct SheetsWorkspace: View {
5 @State private var model: SheetModel
6 @State private var column = NavigationSplitViewColumn.sidebar
7 private struct Panel: Identifiable {
8 let name: String
9 var id: String { name }
10 }
11 @State private var panel: Panel?
12 @State private var query = ""
13 @State private var pendingSheet: SheetSummary?
14 @State private var askDiscard = false
15 @FocusState private var formulaFocused: Bool
16 @Environment(\.scenePhase) private var scenePhase
17 @AppStorage("sheets.appearance") private var appearance = "auto"
18 private let updateRecents: (([(UInt64, String)]) -> Void)?
19 private let canSignOut: Bool
20 @Binding private var accountsRequested: Bool
21 @Binding private var createRequested: Bool
22 private let documentID: UInt64?
23 private let openDocument: ((UInt64, String) -> Void)?
24 private let signOut: () -> Void
25 private let accounts: (() -> Void)?
26 /// "Use another Oficina ID" in the account menu (Paul, 2026-11-19); nil
27 /// for a server account.
28 private let useAnother: (() -> Void)?
29 /// The menu's words for an Oficina ID ("Teams", "Sign out of <label>");
30 /// nil keeps "Accounts" and "Sign out".
31 private let accountsLabel: String?
32 private let signOutLabel: String?
33 /// `client` is any transport: a server account's `NativeHTTP`, or an
34 /// Oficina ID team's `SheetsOficinaTransport`, which reads the latest
35 /// session on every request. Building the model here only constructs it:
36 /// nothing observed is read or written (docs 84d1008).
37 public init(client: any NativeTransport, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: UInt64? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((UInt64, String) -> Void)? = nil, updateRecents: (([(UInt64, String)]) -> Void)? = nil, useAnother: (() -> Void)? = nil, accountsLabel: String? = nil, signOutLabel: String? = nil) {
38 self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument
39 _model = State(initialValue: SheetModel(client: client))
40 self.signOut = signOut
41 self.accounts = accounts
42 self.useAnother = useAnother; self.accountsLabel = accountsLabel; self.signOutLabel = signOutLabel
43 }
44 public var body: some View {
45 Group {
46 #if os(macOS)
47 if documentID != nil { editor } else { home }
48 #else
49 NavigationSplitView(preferredCompactColumn: $column) {
50 library
51 } detail: {
52 if model.page != nil {
53 editor
54 } else {
55 ContentUnavailableView(
56 "Choose a sheet", systemImage: "tablecells",
57 description: Text("Create a spreadsheet or open one from the list."))
58 }
59 }
60 #endif
61 }
62 .onChange(of: model.sheets.map { "\($0.ID)\u{0}\($0.Title)" }) {
63 if query.isEmpty { updateRecents?(model.sheets.map { ($0.ID, $0.Title) }) }
64 }
65 .onChange(of: accountsRequested && !model.busy, initial: true) { _, ready in
66 if ready { accountsRequested = false; accounts?() }
67 }
68 .onChange(of: createRequested, initial: true) { _, requested in
69 if requested && documentID == nil { createRequested = false; Task { await createSheet() } }
70 }
71 .task {
72 if let documentID {
73 await model.open(SheetSummary(ID: documentID, Title: "", TabID: 0, TabName: ""))
74 } else { await model.loadList() }
75 }
76 .onChange(of: model.page?.Sheet.ID) { _, value in if value != nil { column = .detail } }
77 .onChange(of: scenePhase) { _, value in
78 if value != .active { model.clearCopyProvenance() }
79 }
80 .safeAreaInset(edge: .top, spacing: 0) {
81 NativeOfflineBanner(connectivity: model.connectivity, origin: model.client.origin,
82 message: sheetsMacString("You’re offline. Waiting for a connection."))
83 }
84 .task(id: "\(model.page?.Sheet.ID ?? 0)-\(scenePhase == .active)") {
85 if scenePhase == .active { await model.watch() }
86 }
87 .preferredColorScheme(appearance == "dark" ? .dark : appearance == "light" ? .light : nil)
88 #if os(macOS)
89 .background(SheetCloseGuard(model: model).frame(width: 0, height: 0))
90 #endif
91 .sheet(item: $panel) { item in SheetPanels(model: model, panel: item.name, openImported: openDocument) }
92 .confirmationDialog("Keep your cell edit?", isPresented: $askDiscard, titleVisibility: .visible)
93 {
94 Button("Save and continue") {
95 Task {
96 await model.saveAll()
97 if !model.hasUnconfirmedChanges, let next = pendingSheet { await model.open(next) }
98 }
99 }
100 Button("Discard and continue", role: .destructive) {
101 model.discardAll()
102 if let next = pendingSheet { Task { await model.open(next) } }
103 }
104 Button("Cancel", role: .cancel) { pendingSheet = nil }
105 }
106 }
107 private func createSheet() async {
108 #if os(macOS)
109 if let sheet = await model.create(openCreated: false) { openDocument?(sheet.ID, sheet.Title) }
110 #else
111 await model.create()
112 #endif
113 }
114 private var filteredSheets: [SheetSummary] {
115 query.isEmpty ? model.sheets : model.sheets.filter { $0.Title.localizedStandardContains(query) }
116 }
117 private var library: some View {
118 List {
119 if !model.error.isEmpty {
120 Label(model.error, systemImage: "exclamationmark.circle").foregroundStyle(.red)
121 }
122 ForEach(filteredSheets) { sheet in
123 Button {
124 if model.dirty || model.hasFailedEdits {
125 pendingSheet = sheet
126 askDiscard = true
127 } else { Task { await model.open(sheet) } }
128 } label: {
129 HStack(spacing: 16) {
130 SheetThumbnail(sheet.Preview)
131 VStack(alignment: .leading, spacing: 4) {
132 Text(verbatim: sheet.Title).font(.headline).foregroundStyle(.primary)
133 Text(verbatim: sheet.TabName).font(.subheadline).foregroundStyle(.secondary)
134 }
135 Spacer(minLength: 0)
136 Image(systemName: "chevron.right").font(.caption.bold()).foregroundStyle(.tertiary)
137 }.padding(.vertical, 6)
138 }.disabled(model.busy).accessibilityElement(children: .combine)
139 .accessibilityLabel(sheet.Title).accessibilityValue(sheet.TabName)
140 }
141 }
142 .listStyle(.plain)
143 .overlay {
144 if model.listState == .loading { ProgressView() }
145 if model.listState == .loaded && model.sheets.isEmpty {
146 ContentUnavailableView("No spreadsheets", systemImage: "tablecells",
147 description: Text("Create a spreadsheet or import a workbook."))
148 } else if filteredSheets.isEmpty && !query.isEmpty {
149 ContentUnavailableView.search(text: query)
150 }
151 }
152 .navigationTitle("Sheets")
153 .searchable(text: $query, prompt: sheetsMacString("Search spreadsheets"))
154 .refreshable { await model.loadList() }
155 .toolbar {
156 if let accounts {
157 ToolbarItem(placement: .navigation) {
158 Button(accountsLabel ?? sheetsMacString("Accounts"), systemImage: "chevron.backward", action: accounts)
159 .disabled(model.hasUnconfirmedChanges || model.busy)
160 }
161 }
162 ToolbarItem(placement: .primaryAction) {
163 Menu {
164 Button("Import", systemImage: "square.and.arrow.down") { show("Import") }
165 .disabled(model.hasUnconfirmedChanges || model.busy)
166 Picker("Appearance", selection: $appearance) {
167 Text("System").tag("auto")
168 Text("Light").tag("light")
169 Text("Dark").tag("dark")
170 }
171 if let useAnother {
172 Button(OficinaIDText.text("continue.another"), systemImage: "person.crop.circle.badge.plus", action: useAnother)
173 .disabled(model.hasUnconfirmedChanges || model.busy || !canSignOut)
174 }
175 Button(signOutLabel ?? sheetsMacString("Sign out"), systemImage: "rectangle.portrait.and.arrow.right", role: .destructive,
176 action: signOut).disabled(model.hasUnconfirmedChanges || model.busy || !canSignOut)
177 } label: {
178 VStack(spacing: 3) {
179 Circle().frame(width: 3, height: 3)
180 Circle().frame(width: 3, height: 3)
181 Circle().frame(width: 3, height: 3)
182 }.frame(width: 20, height: 20)
183 }.accessibilityLabel("More")
184 }
185 #if os(iOS)
186 DefaultToolbarItem(kind: .search, placement: .bottomBar)
187 ToolbarSpacer(.flexible, placement: .bottomBar)
188 ToolbarItem(placement: .bottomBar) { newSheet }
189 #else
190 ToolbarItem { newSheet }
191 #endif
192 }
193 }
194 private var newSheet: some View {
195 Button(sheetsMacString("New spreadsheet"), systemImage: "plus") { Task { await createSheet() } }
196 .disabled(model.dirty || model.busy)
197 }
198 private func show(_ name: String) {
199 panel = Panel(name: name)
200 }
201 @ViewBuilder private var editorCommands: some View {
202 Menu("File") {
203 Button("Rename") { show("Rename") }.disabled(!model.mayWrite)
204 Button("Export workbook") { show("Export") }.disabled(model.busy || model.dirty)
205 Button("Version history") { show("History") }
206 if model.page?.MayShare == true { Button("Share") { show("Share") } }
207 }
208 Menu("Edit") {
209 Button("Undo my last value edit") { Task { await model.command("/undo") } }.disabled(
210 !model.mayWrite
211 )
212 .keyboardShortcut("z")
213 Button(sheetsMacString("Copy")) { model.copy() }.keyboardShortcut("c")
214 Button(sheetsMacString("Cut")) {
215 model.copy()
216 Task { await model.clear() }
217 }.keyboardShortcut("x").disabled(!model.mayWrite)
218 Button(sheetsMacString("Paste")) { Task { await model.paste() } }.keyboardShortcut("v").disabled(
219 !model.mayWrite)
220 Button(sheetsMacString("Clear contents")) { Task { await model.clear() } }.disabled(!model.mayWrite)
221 Button(sheetsMacString("Fill down")) { Task { await model.fill(down: true) } }.keyboardShortcut("d").disabled(
222 !model.mayWrite)
223 Button(sheetsMacString("Fill right")) { Task { await model.fill(down: false) } }.disabled(!model.mayWrite)
224 Button(sheetsMacString("Select all")) {
225 model.rangeText = "A1:" + Coordinate(r: model.rows - 1, c: model.cols - 1).ref
226 model.selectRange()
227 }.keyboardShortcut("a")
228 }.disabled(model.dirty || model.busy)
229 Menu("Insert function") {
230 ForEach(["SUM", "AVERAGE", "COUNT", "MIN", "MAX"], id: \.self) { name in
231 Button(name) { Task { await model.insertFunction(name) } }
232 }
233 }.disabled(!model.mayWrite || model.dirty || model.busy)
234 SheetFormatMenu(model: model)
235 Button("Sizes") { show("Sizes") }.disabled(
236 !model.mayWrite || model.dirty || model.busy)
237 Button("Sort and filter") { show("Data") }.disabled(
238 model.dirty || model.busy)
239 Button("Comments") { show("Comments") }
240 Button(sheetsMacString("Refresh"), systemImage: "arrow.clockwise") { Task { await model.refresh() } }
241 }
242 private var editor: some View {
243 VStack(spacing: 0) {
244 #if os(iOS)
245 ViewThatFits(in: .horizontal) {
246 HStack { editorCommands }.fixedSize(horizontal: true, vertical: false)
247 Menu("Sheet actions", systemImage: "ellipsis.circle") { editorCommands }
248 .frame(maxWidth: .infinity, alignment: .leading)
249 }.padding(8)
250 #endif
251 SheetFormulaBar(model: model, formulaFocused: $formulaFocused)
252 SheetFailedEditsBar(model: model)
253 if !model.error.isEmpty {
254 Text(model.error).foregroundStyle(.red).padding(8).accessibilityAddTraits(
255 .updatesFrequently)
256 }
257 if model.showTable {
258 SheetTable(model: model)
259 } else {
260 SheetGrid(model: model, beginEditing: { formulaFocused = true })
261 }
262 SheetStatusBar(model: model)
263 if model.page?.Truncated == true {
264 Text("This grid shows up to 500 rows and 200 columns. Export includes the complete sheet.")
265 .font(.caption).padding(4)
266 }
267 if !(model.page?.Warned ?? []).isEmpty {
268 Text(
269 "Imported colours have low contrast in: "
270 + (model.page?.Warned ?? []).joined(separator: ", ")
271 ).font(.caption).padding(4)
272 }
273 }.navigationTitle(model.page?.Sheet.Title ?? "Sheets")
274 #if os(macOS)
275 .focusedSceneValue(\.sheetEditor, SheetEditorContext(model: model, panel: Binding(get: { panel?.name }, set: { panel = $0.map { Panel(name: $0) } })))
276 #endif
277 #if os(iOS)
278 .navigationBarTitleDisplayMode(.inline)
279 #endif
280 }
281 #if os(macOS)
282 private var home: some View {
283 NavigationSplitView {
284 List { Label(sheetsMacString("Recent"), systemImage: "clock").listRowBackground(Color.accentColor.opacity(0.12)) }
285 .navigationSplitViewColumnWidth(min: 160, ideal: 190, max: 240)
286 } detail: {
287 ScrollView {
288 VStack(alignment: .leading, spacing: 24) {
289 Text(sheetsMacString("Recent spreadsheets")).font(.largeTitle.bold())
290 if !model.error.isEmpty { Text(model.error).foregroundStyle(.red) }
291 LazyVGrid(columns: [GridItem(.adaptive(minimum: 200, maximum: 260))], spacing: 24) {
292 ForEach(filteredSheets) { sheet in
293 Button { openDocument?(sheet.ID, sheet.Title) } label: {
294 VStack(alignment: .leading, spacing: 10) {
295 SheetThumbnail(sheet.Preview, width: 200, height: 150)
296 .background(.background).clipShape(.rect(cornerRadius: 5))
297 Text(sheet.Title).font(.headline).lineLimit(2)
298 Text(sheet.TabName).font(.caption).foregroundStyle(.secondary)
299 }.frame(maxWidth: .infinity, alignment: .leading).padding(12)
300 }.buttonStyle(.plain)
301 }
302 }
303 if model.listState == .loading { ProgressView().frame(maxWidth: .infinity) }
304 if model.listState == .loaded && model.sheets.isEmpty {
305 ContentUnavailableView("No spreadsheets", systemImage: "tablecells", description: Text("Create a spreadsheet or import a workbook."))
306 }
307 }.padding(28)
308 }
309 .navigationTitle(sheetsMacString("Home"))
310 .searchable(text: $query, prompt: sheetsMacString("Search spreadsheets"))
311 .focusedSceneValue(\.sheetsAccountActions, SheetsAccountActions(accounts: accounts, signOut: signOut, canManage: !model.busy, canSignOut: canSignOut && !model.busy,
312 useAnother: useAnother, accountsLabel: accountsLabel, signOutLabel: signOutLabel))
313 .toolbar {
314 newSheet
315 Button(sheetsMacString("Import workbook")) { show("Import") }
316 Button(sheetsMacString("Refresh"), systemImage: "arrow.clockwise") { Task { await model.loadList() } }
317 }
318 }
319 }
320 #endif
321
322}
323