Sources/OrgstarMobile/FoldersScreen.swift

974c897ecb48b138c67b0c0e8115887978db2b89
orgstar/Sources/OrgstarMobile/FoldersScreen.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form