Sources/OrgstarMobile/FoldersScreen.swift

3e8222e0d8292697893ada687b8aaca04779bae8
orgstar/Sources/OrgstarMobile/FoldersScreen.swift

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