Sources/OrgstarMobile/FoldersScreen.swift
cmc One capitalisation rule: title case for titles and buttons, sentence case for settings
7c1313ad9f 15 hours ago358 lines · 17661 bytes
1#if os(iOS)
2import OrgApp
3import SwiftUI
4import UniformTypeIdentifiers
5
6/// The folders of org files the agenda reads, and their files.
7struct FoldersScreen: View {
8 let workspace: WorkspaceModel
9 let session: DocumentSession
10 /// The file whose deletion is being confirmed.
11 @State private var deleting: String?
12 /// Counts deletions and new folders, so the list reads the empty folders on disk again.
13 @State private var changes = 0
14 @State private var creating: NewItem?
15 /// The added folder whose deletion from disk is being confirmed.
16 @State private var deletingRoot: String?
17 /// The added folder whose removal from orgstar is being confirmed.
18 @State private var removingRoot: String?
19 @Environment(MobileModel.self) private var model
20
21 var body: some View {
22 List {
23 ForEach(workspace.rootPaths, id: \.self) { root in
24 Section {
25 FolderContents(workspace: workspace, root: root, folder: "", deleting: $deleting, changes: changes)
26 if isEmptyFolder(root) {
27 Button("Delete Folder…", role: .destructive) { deletingRoot = root }
28 }
29 } header: {
30 // A header takes no swipe, so its menu holds the folder's own actions.
31 HStack {
32 Text((root as NSString).lastPathComponent)
33 Spacer()
34 Menu {
35 removeButton(root)
36 } label: {
37 Label("Folder Actions", systemImage: "ellipsis.circle").labelStyle(.iconOnly)
38 }
39 .textCase(nil)
40 }
41 .contextMenu { removeButton(root) }
42 }
43 }
44 if let error = workspace.lastError {
45 // The title says what failed.
46 Text(workspace.lastErrorTitle.map { "\($0)\n\(error)" } ?? error).foregroundStyle(.red)
47 }
48 }
49 .navigationTitle("Folders")
50 .confirmationDialog("Delete “\(deletingRoot.map { ($0 as NSString).lastPathComponent } ?? "")”?",
51 isPresented: Binding { deletingRoot != nil } set: { if !$0 { deletingRoot = nil } }, titleVisibility: .visible) {
52 Button("Delete", role: .destructive) {
53 guard let root = deletingRoot else { return }
54 deletingRoot = nil
55 Task {
56 do {
57 try await workspace.trash(root)
58 try workspace.removeRoot(path: root)
59 } catch {
60 workspace.showError(String(localized: "Couldn't Delete Folder", comment: "Error alert title"), error.localizedDescription)
61 }
62 }
63 }
64 } message: {
65 Text("The empty folder is removed from disk and from orgstar.")
66 }
67 .confirmationDialog("Remove “\(removingRoot.map { ($0 as NSString).lastPathComponent } ?? "")” from orgstar?",
68 isPresented: Binding { removingRoot != nil } set: { if !$0 { removingRoot = nil } }, titleVisibility: .visible) {
69 Button("Remove from orgstar", role: .destructive) {
70 guard let root = removingRoot else { return }
71 removingRoot = nil
72 try? workspace.removeRoot(path: root)
73 }
74 } message: {
75 Text("The folder and its files stay where they are. orgstar stops reading them, and the agenda leaves them out.")
76 }
77 .navigationDestination(for: FolderRoute.self) { route in
78 FolderPage(workspace: workspace, session: session, route: route)
79 }
80 .confirmDeletion($deleting, workspace: workspace, session: session) { changes += 1 }
81 .createItem($creating, workspace: workspace) { changes += 1 }
82 .overlay {
83 if workspace.rootPaths.isEmpty {
84 ContentUnavailableView {
85 Label("No Folders", systemImage: "folder")
86 } description: {
87 Text("Add the folder your org files are in, from iCloud Drive or another app's storage.")
88 } actions: {
89 Button("Add Folder") { model.addingFolder = true }
90 }
91 }
92 }
93 .toolbar {
94 ToolbarItem(placement: .topBarLeading) {
95 Button("Add Folder", systemImage: "folder.badge.plus") { model.addingFolder = true }
96 }
97 if !workspace.rootPaths.isEmpty {
98 ToolbarItem(placement: .primaryAction) {
99 Menu("Daily Notes", systemImage: "calendar") {
100 Button("Today", systemImage: "calendar") { dailies("app.dailies.today") }
101 Button("Yesterday", systemImage: "chevron.backward") { dailies("app.dailies.yesterday") }
102 Button("Tomorrow", systemImage: "chevron.forward") { dailies("app.dailies.tomorrow") }
103 }
104 }
105 ToolbarItem(placement: .primaryAction) {
106 Menu("New", systemImage: "plus") {
107 // One added folder takes them directly; several each get a submenu.
108 if workspace.rootPaths.count == 1, let root = workspace.rootPaths.first {
109 newItems(in: root)
110 } else {
111 ForEach(workspace.rootPaths, id: \.self) { root in
112 Menu((root as NSString).lastPathComponent) { newItems(in: root) }
113 }
114 }
115 }
116 }
117 }
118 }
119 .fileImporter(isPresented: Bindable(model).addingFolder, allowedContentTypes: [.folder]) { result in
120 guard case .success(let url) = result else { return }
121 // Kept for the bookmark; WorkspaceRoot resolves it with access again at launch.
122 _ = url.startAccessingSecurityScopedResource()
123 Task {
124 do {
125 try await workspace.addRoot(url)
126 } catch {
127 workspace.showError(String(localized: "Couldn't Add Folder", comment: "Error alert title"), error.localizedDescription)
128 }
129 }
130 }
131 }
132}
133extension FoldersScreen {
134 private func removeButton(_ root: String) -> some View {
135 Button("Remove from orgstar…", systemImage: "folder.badge.minus", role: .destructive) { removingRoot = root }
136 }
137
138 /// A daily note, opened in the reader.
139 private func dailies(_ id: String) {
140 guard ProAccess.shared.allows(.roam) else { return }
141 RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { [] }, show: { workspace.lastError = $0 }, ask: { $1(nil) },
142 open: { path, offset in model.openRequest = .offset(path, offset) }, insertLink: { _, _ in },
143 refresh: { Task { await workspace.refresh() } }).run(id)
144 }
145}
146
147/// A subfolder's own list, asking about its own changes; an added folder's, from the iPad's
148/// sidebar.
149struct FolderPage: View {
150 let workspace: WorkspaceModel
151 let session: DocumentSession
152 let route: FolderRoute
153 @State private var deleting: String?
154 @State private var changes = 0
155 @State private var creating: NewItem?
156
157 var body: some View {
158 let folder = route.folder.isEmpty ? route.root : route.root + "/" + route.folder
159 List { FolderContents(workspace: workspace, root: route.root, folder: route.folder, deleting: $deleting, changes: changes) }
160 .navigationTitle(((route.folder.isEmpty ? route.root : route.folder) as NSString).lastPathComponent)
161 .confirmDeletion($deleting, workspace: workspace, session: session) { changes += 1 }
162 .createItem($creating, workspace: workspace) { changes += 1 }
163 .toolbar {
164 ToolbarItem(placement: .primaryAction) {
165 Menu("New", systemImage: "plus") {
166 Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) }
167 Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) }
168 }
169 }
170 }
171 }
172}
173
174/// A file or folder to create in `folder`, named in an alert.
175private struct NewItem: Identifiable {
176 let folder: String
177 let isFolder: Bool
178 var id: String { folder + (isFolder ? "/" : "") }
179}
180
181/// The alert naming a new file or folder.
182private struct NewItemAlert: ViewModifier {
183 @Binding var creating: NewItem?
184 let workspace: WorkspaceModel
185 let created: () -> Void
186 @State private var name = ""
187
188 func body(content: Content) -> some View {
189 content.alert(creating?.isFolder == true ? "New Folder" : "New File", isPresented: Binding { creating != nil } set: { if !$0 { creating = nil } }) {
190 TextField("Name", text: $name)
191 .autocorrectionDisabled()
192 .textInputAutocapitalization(.never)
193 Button("Create") {
194 guard let item = creating else { return }
195 let typed = name
196 name = ""
197 Task {
198 do {
199 if item.isFolder { try Self.makeFolder(typed, in: item.folder) } else { _ = try await workspace.createFile(named: typed, in: item.folder) }
200 created()
201 } catch {
202 workspace.showError(item.isFolder ? String(localized: "Couldn't Create Folder", comment: "Error alert title")
203 : String(localized: "Couldn't Create File", comment: "Error alert title"), error.localizedDescription)
204 }
205 }
206 }
207 Button("Cancel", role: .cancel) { name = "" }
208 } message: {
209 if creating?.isFolder != true { Text("A name without an extension gets .org.") }
210 }
211 }
212
213 static func makeFolder(_ name: String, in folder: String) throws {
214 let trimmed = name.trimmingCharacters(in: .whitespaces)
215 guard !trimmed.isEmpty, !trimmed.contains("/"), !trimmed.hasPrefix(".") else {
216 throw WorkspaceModel.FileError(message: "Not a folder name: \(name)")
217 }
218 let url = URL(fileURLWithPath: folder).appendingPathComponent(trimmed)
219 guard !FileManager.default.fileExists(atPath: url.path) else { throw WorkspaceModel.FileError(message: "\(trimmed) already exists.") }
220 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
221 }
222}
223
224private extension View {
225 func createItem(_ creating: Binding<NewItem?>, workspace: WorkspaceModel, created: @escaping () -> Void) -> some View {
226 modifier(NewItemAlert(creating: creating, workspace: workspace, created: created))
227 }
228
229 /// Asks before deleting the file or empty folder in `deleting`, closing a file first.
230 func confirmDeletion(_ deleting: Binding<String?>, workspace: WorkspaceModel, session: DocumentSession, deleted: @escaping () -> Void) -> some View {
231 let name = deleting.wrappedValue.map { ($0 as NSString).lastPathComponent } ?? ""
232 var isFolder: ObjCBool = false
233 let folder = deleting.wrappedValue.map { FileManager.default.fileExists(atPath: $0, isDirectory: &isFolder) && isFolder.boolValue } ?? false
234 return confirmationDialog("Delete “\(name)”?", isPresented: Binding { deleting.wrappedValue != nil } set: { if !$0 { deleting.wrappedValue = nil } },
235 titleVisibility: .visible) {
236 Button("Delete", role: .destructive) {
237 guard let path = deleting.wrappedValue else { return }
238 deleting.wrappedValue = nil
239 session.kill(path)
240 Task {
241 do { try await workspace.trash(path) } catch {
242 workspace.showError(folder ? String(localized: "Couldn't Delete Folder", comment: "Error alert title")
243 : String(localized: "Couldn't Delete File", comment: "Error alert title"), error.localizedDescription)
244 }
245 deleted()
246 }
247 }
248 } message: {
249 Text(folder ? "The empty folder is removed." : "The whole file is removed. Files in iCloud Drive go to Recently Deleted in the Files app.")
250 }
251 }
252}
253
254extension FoldersScreen {
255 @ViewBuilder
256 private func newItems(in folder: String) -> some View {
257 Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) }
258 Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) }
259 }
260}
261
262/// A folder with nothing in it but dotfiles.
263private func isEmptyFolder(_ path: String) -> Bool {
264 guard let inside = try? FileManager.default.contentsOfDirectory(atPath: path) else { return false }
265 return inside.allSatisfy { $0.hasPrefix(".") }
266}
267
268/// A subfolder to show, relative to its root.
269struct FolderRoute: Hashable {
270 let root: String
271 let folder: String
272}
273
274/// One folder's subfolders, which open their own contents, then its org files and the files
275/// still downloading into it. `folder` is relative to `root`, empty for the root itself.
276private struct FolderContents: View {
277 let workspace: WorkspaceModel
278 let root: String
279 let folder: String
280 @Binding var deleting: String?
281 /// Changes after each deletion, which the index may not show, so empty folders are read again.
282 let changes: Int
283 /// Files not yet downloaded that were tapped, shown with a spinner until they arrive.
284 @State private var requested: Set<String> = []
285
286 private var prefix: String { folder.isEmpty ? "" : folder + "/" }
287
288 /// Subfolders on disk with nothing in them but dotfiles, which the index, built from
289 /// files, doesn't know of.
290 private func emptySubfolders() -> [String] {
291 let fm = FileManager.default
292 let url = URL(fileURLWithPath: root).appendingPathComponent(folder)
293 guard let names = try? fm.contentsOfDirectory(atPath: url.path) else { return [] }
294 return names.filter { name in
295 var isFolder: ObjCBool = false
296 let path = url.appendingPathComponent(name).path
297 return !name.hasPrefix(".") && fm.fileExists(atPath: path, isDirectory: &isFolder) && isFolder.boolValue && isEmptyFolder(path)
298 }
299 }
300
301 /// Paths below this folder, relative to it.
302 private func below(_ relativePaths: [String]) -> [String] {
303 relativePaths.filter { $0.hasPrefix(prefix) }.map { String($0.dropFirst(prefix.count)) }
304 }
305
306 var body: some View {
307 let files = workspace.files.filter { $0.root == root && $0.kind == .org && $0.relativePath.hasPrefix(prefix) }
308 let pending = below(workspace.downloading.filter { $0.hasPrefix(root + "/") }.map { String($0.dropFirst(root.count + 1)) })
309 let empty = Set(emptySubfolders())
310 let subfolders = Set((below(files.map(\.relativePath)) + pending).compactMap { path in
311 path.firstIndex(of: "/").map { String(path[..<$0]) }
312 }).union(empty).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
313 ForEach(subfolders, id: \.self) { name in
314 // A value, as the files' links are: a stack mixing the two kinds pushes wrongly.
315 NavigationLink(value: FolderRoute(root: root, folder: prefix + name)) {
316 Label(name, systemImage: "folder")
317 }
318 .swipeActions(edge: .trailing) {
319 if empty.contains(name) {
320 Button("Delete", systemImage: "trash") { deleting = root + "/" + prefix + name }.tint(.red)
321 }
322 }
323 .contextMenu {
324 if empty.contains(name) {
325 Button("Delete…", systemImage: "trash", role: .destructive) { deleting = root + "/" + prefix + name }
326 }
327 }
328 }
329 ForEach(files.filter { !$0.relativePath.dropFirst(prefix.count).contains("/") }) { file in
330 NavigationLink(value: ReaderRoute.file(file.path)) {
331 Label(file.name, systemImage: "doc.text")
332 }
333 .swipeActions(edge: .trailing) {
334 Button("Delete", systemImage: "trash") { deleting = file.path }.tint(.red)
335 }
336 .contextMenu {
337 Button("Delete…", systemImage: "trash", role: .destructive) { deleting = file.path }
338 }
339 }
340 ForEach(pending.filter { !$0.contains("/") }, id: \.self) { name in
341 let path = root + "/" + prefix + name
342 Button {
343 // iCloud downloads these by itself in time; a tap asks for this one now.
344 try? FileManager.default.startDownloadingUbiquitousItem(at: URL(fileURLWithPath: path))
345 requested.insert(path)
346 } label: {
347 HStack {
348 Label(name, systemImage: "icloud.and.arrow.down")
349 Spacer()
350 if requested.contains(path) { ProgressView() }
351 }
352 .foregroundStyle(.secondary)
353 }
354 .accessibilityHint(requested.contains(path) ? Text("Downloading") : Text("Downloads the file from iCloud"))
355 }
356 }
357}
358#endif