Sources/OrgstarMobile/FoldersScreen.swift

ca2e56c4b63f0ed22f5b87729efc41b1c270fa19
orgstar/Sources/OrgstarMobile/FoldersScreen.swift

265 lines · 12449 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 and new folders, so the list reads the empty folders on disk again.
 14    @State private var changes = 0
 15    @State private var creating: NewItem?
 16
 17    var body: some View {
 18        List {
 19            ForEach(workspace.rootPaths, id: \.self) { root in
 20                Section((root as NSString).lastPathComponent) {
 21                    FolderContents(workspace: workspace, root: root, folder: "", deleting: $deleting, changes: changes)
 22                    Button("Remove Folder", role: .destructive) { try? workspace.removeRoot(path: root) }
 23                }
 24            }
 25            if let error = workspace.lastError {
 26                Text(error).foregroundStyle(.red)
 27            }
 28        }
 29        .navigationTitle("Folders")
 30        .navigationDestination(for: FolderRoute.self) { route in
 31            FolderPage(workspace: workspace, session: session, route: route)
 32        }
 33        .confirmDeletion($deleting, workspace: workspace, session: session) { changes += 1 }
 34        .createItem($creating, workspace: workspace) { changes += 1 }
 35        .overlay {
 36            if workspace.rootPaths.isEmpty {
 37                ContentUnavailableView {
 38                    Label("No folders", systemImage: "folder")
 39                } description: {
 40                    Text("Add the folder your org files are in, from iCloud Drive or another app's storage.")
 41                } actions: {
 42                    Button("Add Folder") { importing = true }
 43                }
 44            }
 45        }
 46        .toolbar {
 47            ToolbarItem(placement: .topBarLeading) {
 48                Button("Add Folder", systemImage: "folder.badge.plus") { importing = true }
 49            }
 50            if !workspace.rootPaths.isEmpty {
 51                ToolbarItem(placement: .primaryAction) {
 52                    Menu("New", systemImage: "plus") {
 53                        // One added folder takes them directly; several each get a submenu.
 54                        if workspace.rootPaths.count == 1, let root = workspace.rootPaths.first {
 55                            newItems(in: root)
 56                        } else {
 57                            ForEach(workspace.rootPaths, id: \.self) { root in
 58                                Menu((root as NSString).lastPathComponent) { newItems(in: root) }
 59                            }
 60                        }
 61                    }
 62                }
 63            }
 64        }
 65        .fileImporter(isPresented: $importing, allowedContentTypes: [.folder]) { result in
 66            guard case .success(let url) = result else { return }
 67            // Kept for the bookmark; WorkspaceRoot resolves it with access again at launch.
 68            _ = url.startAccessingSecurityScopedResource()
 69            Task {
 70                do {
 71                    try await workspace.addRoot(url)
 72                } catch {
 73                    workspace.lastError = "Can't add \(url.lastPathComponent): \(error.localizedDescription)"
 74                }
 75            }
 76        }
 77    }
 78}
 79/// A subfolder's own list, asking about its own changes.
 80private struct FolderPage: View {
 81    let workspace: WorkspaceModel
 82    let session: DocumentSession
 83    let route: FolderRoute
 84    @State private var deleting: String?
 85    @State private var changes = 0
 86    @State private var creating: NewItem?
 87
 88    var body: some View {
 89        let folder = route.root + "/" + route.folder
 90        List { FolderContents(workspace: workspace, root: route.root, folder: route.folder, deleting: $deleting, changes: changes) }
 91            .navigationTitle((route.folder as NSString).lastPathComponent)
 92            .confirmDeletion($deleting, workspace: workspace, session: session) { changes += 1 }
 93            .createItem($creating, workspace: workspace) { changes += 1 }
 94            .toolbar {
 95                ToolbarItem(placement: .primaryAction) {
 96                    Menu("New", systemImage: "plus") {
 97                        Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) }
 98                        Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) }
 99                    }
100                }
101            }
102    }
103}
104
105/// A file or folder to create in `folder`, named in an alert.
106private struct NewItem: Identifiable {
107    let folder: String
108    let isFolder: Bool
109    var id: String { folder + (isFolder ? "/" : "") }
110}
111
112/// The alert naming a new file or folder.
113private struct NewItemAlert: ViewModifier {
114    @Binding var creating: NewItem?
115    let workspace: WorkspaceModel
116    let created: () -> Void
117    @State private var name = ""
118
119    func body(content: Content) -> some View {
120        content.alert(creating?.isFolder == true ? "New Folder" : "New File", isPresented: Binding { creating != nil } set: { if !$0 { creating = nil } }) {
121            TextField("Name", text: $name)
122                .autocorrectionDisabled()
123                .textInputAutocapitalization(.never)
124            Button("Create") {
125                guard let item = creating else { return }
126                let typed = name
127                name = ""
128                Task {
129                    do {
130                        if item.isFolder { try Self.makeFolder(typed, in: item.folder) } else { _ = try await workspace.createFile(named: typed, in: item.folder) }
131                        created()
132                    } catch {
133                        workspace.lastError = error.localizedDescription
134                    }
135                }
136            }
137            Button("Cancel", role: .cancel) { name = "" }
138        } message: {
139            if creating?.isFolder != true { Text("A name without an extension gets .org.") }
140        }
141    }
142
143    static func makeFolder(_ name: String, in folder: String) throws {
144        let trimmed = name.trimmingCharacters(in: .whitespaces)
145        guard !trimmed.isEmpty, !trimmed.contains("/"), !trimmed.hasPrefix(".") else {
146            throw WorkspaceModel.FileError(message: "Not a folder name: \(name)")
147        }
148        let url = URL(fileURLWithPath: folder).appendingPathComponent(trimmed)
149        guard !FileManager.default.fileExists(atPath: url.path) else { throw WorkspaceModel.FileError(message: "\(trimmed) already exists.") }
150        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
151    }
152}
153
154private extension View {
155    func createItem(_ creating: Binding<NewItem?>, workspace: WorkspaceModel, created: @escaping () -> Void) -> some View {
156        modifier(NewItemAlert(creating: creating, workspace: workspace, created: created))
157    }
158
159    /// Asks before deleting the file or empty folder in `deleting`, closing a file first.
160    func confirmDeletion(_ deleting: Binding<String?>, workspace: WorkspaceModel, session: DocumentSession, deleted: @escaping () -> Void) -> some View {
161        let name = deleting.wrappedValue.map { ($0 as NSString).lastPathComponent } ?? ""
162        var isFolder: ObjCBool = false
163        let folder = deleting.wrappedValue.map { FileManager.default.fileExists(atPath: $0, isDirectory: &isFolder) && isFolder.boolValue } ?? false
164        return confirmationDialog("Delete “\(name)”?", isPresented: Binding { deleting.wrappedValue != nil } set: { if !$0 { deleting.wrappedValue = nil } },
165                                  titleVisibility: .visible) {
166            Button("Delete", role: .destructive) {
167                guard let path = deleting.wrappedValue else { return }
168                deleting.wrappedValue = nil
169                session.kill(path)
170                Task {
171                    do { try await workspace.trash(path) } catch { workspace.lastError = "Can't delete \(name): \(error.localizedDescription)" }
172                    deleted()
173                }
174            }
175        } message: {
176            Text(folder ? "The empty folder is removed." : "The whole file is removed. Files in iCloud Drive go to Recently Deleted in the Files app.")
177        }
178    }
179}
180
181extension FoldersScreen {
182    @ViewBuilder
183    private func newItems(in folder: String) -> some View {
184        Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) }
185        Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) }
186    }
187}
188
189/// A subfolder to show, relative to its root.
190struct FolderRoute: Hashable {
191    let root: String
192    let folder: String
193}
194
195/// One folder's subfolders, which open their own contents, then its org files and the files
196/// still downloading into it. `folder` is relative to `root`, empty for the root itself.
197private struct FolderContents: View {
198    let workspace: WorkspaceModel
199    let root: String
200    let folder: String
201    @Binding var deleting: String?
202    /// Changes after each deletion, which the index may not show, so empty folders are read again.
203    let changes: Int
204
205    private var prefix: String { folder.isEmpty ? "" : folder + "/" }
206
207    /// Subfolders on disk with nothing in them but dotfiles, which the index, built from
208    /// files, doesn't know of.
209    private func emptySubfolders() -> [String] {
210        let fm = FileManager.default
211        let url = URL(fileURLWithPath: root).appendingPathComponent(folder)
212        guard let names = try? fm.contentsOfDirectory(atPath: url.path) else { return [] }
213        return names.filter { name in
214            var isFolder: ObjCBool = false
215            guard !name.hasPrefix("."), fm.fileExists(atPath: url.appendingPathComponent(name).path, isDirectory: &isFolder), isFolder.boolValue,
216                  let inside = try? fm.contentsOfDirectory(atPath: url.appendingPathComponent(name).path) else { return false }
217            return inside.allSatisfy { $0.hasPrefix(".") }
218        }
219    }
220
221    /// Paths below this folder, relative to it.
222    private func below(_ relativePaths: [String]) -> [String] {
223        relativePaths.filter { $0.hasPrefix(prefix) }.map { String($0.dropFirst(prefix.count)) }
224    }
225
226    var body: some View {
227        let files = workspace.files.filter { $0.root == root && $0.kind == .org && $0.relativePath.hasPrefix(prefix) }
228        let pending = below(workspace.downloading.filter { $0.hasPrefix(root + "/") }.map { String($0.dropFirst(root.count + 1)) })
229        let empty = Set(emptySubfolders())
230        let subfolders = Set((below(files.map(\.relativePath)) + pending).compactMap { path in
231            path.firstIndex(of: "/").map { String(path[..<$0]) }
232        }).union(empty).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
233        ForEach(subfolders, id: \.self) { name in
234            // A value, as the files' links are: a stack mixing the two kinds pushes wrongly.
235            NavigationLink(value: FolderRoute(root: root, folder: prefix + name)) {
236                Label(name, systemImage: "folder")
237            }
238            .swipeActions(edge: .trailing) {
239                if empty.contains(name) {
240                    Button("Delete", systemImage: "trash") { deleting = root + "/" + prefix + name }.tint(.red)
241                }
242            }
243            .contextMenu {
244                if empty.contains(name) {
245                    Button("Delete…", systemImage: "trash", role: .destructive) { deleting = root + "/" + prefix + name }
246                }
247            }
248        }
249        ForEach(files.filter { !$0.relativePath.dropFirst(prefix.count).contains("/") }) { file in
250            NavigationLink(value: ReaderRoute.file(file.path)) {
251                Label(file.name, systemImage: "doc.text")
252            }
253            .swipeActions(edge: .trailing) {
254                Button("Delete", systemImage: "trash") { deleting = file.path }.tint(.red)
255            }
256            .contextMenu {
257                Button("Delete…", systemImage: "trash", role: .destructive) { deleting = file.path }
258            }
259        }
260        ForEach(pending.filter { !$0.contains("/") }, id: \.self) { name in
261            Label(name, systemImage: "icloud.and.arrow.down").foregroundStyle(.secondary)
262        }
263    }
264}
265#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