Sources/OrgstarMobile/FoldersScreen.swift

ec53628273f55cd59d0f0f84327235bd7554900f
orgstar/Sources/OrgstarMobile/FoldersScreen.swift

144 lines · 6296 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    @State private var importing = false
 11    /// The file whose deletion is being confirmed.
 12    @State private var deleting: String?
 13
 14    var body: some View {
 15        List {
 16            ForEach(workspace.rootPaths, id: \.self) { root in
 17                Section((root as NSString).lastPathComponent) {
 18                    FolderContents(workspace: workspace, root: root, folder: "", deleting: $deleting)
 19                    Button("Remove Folder", role: .destructive) { try? workspace.removeRoot(path: root) }
 20                }
 21            }
 22            if let error = workspace.lastError {
 23                Text(error).foregroundStyle(.red)
 24            }
 25        }
 26        .navigationTitle("Folders")
 27        .navigationDestination(for: FolderRoute.self) { route in
 28            FolderPage(workspace: workspace, session: session, route: route)
 29        }
 30        .confirmDeletion($deleting, workspace: workspace, session: session)
 31        .overlay {
 32            if workspace.rootPaths.isEmpty {
 33                ContentUnavailableView {
 34                    Label("No folders", systemImage: "folder")
 35                } description: {
 36                    Text("Add the folder your org files are in, from iCloud Drive or another app's storage.")
 37                } actions: {
 38                    Button("Add Folder") { importing = true }
 39                }
 40            }
 41        }
 42        .toolbar {
 43            ToolbarItem(placement: .topBarLeading) {
 44                Button("Add Folder", systemImage: "folder.badge.plus") { importing = true }
 45            }
 46        }
 47        .fileImporter(isPresented: $importing, allowedContentTypes: [.folder]) { result in
 48            guard case .success(let url) = result else { return }
 49            // Kept for the bookmark; WorkspaceRoot resolves it with access again at launch.
 50            _ = url.startAccessingSecurityScopedResource()
 51            Task {
 52                do {
 53                    try await workspace.addRoot(url)
 54                } catch {
 55                    workspace.lastError = "Can't add \(url.lastPathComponent): \(error.localizedDescription)"
 56                }
 57            }
 58        }
 59    }
 60}
 61/// A subfolder's own list, asking about its own deletions.
 62private struct FolderPage: View {
 63    let workspace: WorkspaceModel
 64    let session: DocumentSession
 65    let route: FolderRoute
 66    @State private var deleting: String?
 67
 68    var body: some View {
 69        List { FolderContents(workspace: workspace, root: route.root, folder: route.folder, deleting: $deleting) }
 70            .navigationTitle((route.folder as NSString).lastPathComponent)
 71            .confirmDeletion($deleting, workspace: workspace, session: session)
 72    }
 73}
 74
 75private extension View {
 76    /// Asks before deleting the file in `deleting`, closing it first.
 77    func confirmDeletion(_ deleting: Binding<String?>, workspace: WorkspaceModel, session: DocumentSession) -> some View {
 78        let name = deleting.wrappedValue.map { ($0 as NSString).lastPathComponent } ?? ""
 79        return confirmationDialog("Delete “\(name)”?", isPresented: Binding { deleting.wrappedValue != nil } set: { if !$0 { deleting.wrappedValue = nil } },
 80                                  titleVisibility: .visible) {
 81            Button("Delete", role: .destructive) {
 82                guard let path = deleting.wrappedValue else { return }
 83                deleting.wrappedValue = nil
 84                session.kill(path)
 85                Task {
 86                    do { try await workspace.trash(path) } catch { workspace.lastError = "Can't delete \(name): \(error.localizedDescription)" }
 87                }
 88            }
 89        } message: {
 90            Text("The whole file is removed. Files in iCloud Drive go to Recently Deleted in the Files app.")
 91        }
 92    }
 93}
 94
 95/// A subfolder to show, relative to its root.
 96struct FolderRoute: Hashable {
 97    let root: String
 98    let folder: String
 99}
100
101/// One folder's subfolders, which open their own contents, then its org files and the files
102/// still downloading into it. `folder` is relative to `root`, empty for the root itself.
103private struct FolderContents: View {
104    let workspace: WorkspaceModel
105    let root: String
106    let folder: String
107    @Binding var deleting: String?
108
109    private var prefix: String { folder.isEmpty ? "" : folder + "/" }
110
111    /// Paths below this folder, relative to it.
112    private func below(_ relativePaths: [String]) -> [String] {
113        relativePaths.filter { $0.hasPrefix(prefix) }.map { String($0.dropFirst(prefix.count)) }
114    }
115
116    var body: some View {
117        let files = workspace.files.filter { $0.root == root && $0.kind == .org && $0.relativePath.hasPrefix(prefix) }
118        let pending = below(workspace.downloading.filter { $0.hasPrefix(root + "/") }.map { String($0.dropFirst(root.count + 1)) })
119        let subfolders = Set((below(files.map(\.relativePath)) + pending).compactMap { path in
120            path.firstIndex(of: "/").map { String(path[..<$0]) }
121        }).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
122        ForEach(subfolders, id: \.self) { name in
123            // A value, as the files' links are: a stack mixing the two kinds pushes wrongly.
124            NavigationLink(value: FolderRoute(root: root, folder: prefix + name)) {
125                Label(name, systemImage: "folder")
126            }
127        }
128        ForEach(files.filter { !$0.relativePath.dropFirst(prefix.count).contains("/") }) { file in
129            NavigationLink(value: ReaderRoute.file(file.path)) {
130                Label(file.name, systemImage: "doc.text")
131            }
132            .swipeActions(edge: .trailing) {
133                Button("Delete", systemImage: "trash") { deleting = file.path }.tint(.red)
134            }
135            .contextMenu {
136                Button("Delete…", systemImage: "trash", role: .destructive) { deleting = file.path }
137            }
138        }
139        ForEach(pending.filter { !$0.contains("/") }, id: \.self) { name in
140            Label(name, systemImage: "icloud.and.arrow.down").foregroundStyle(.secondary)
141        }
142    }
143}
144#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