Sources/OrgstarMobile/FoldersScreen.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgstarMobile/FoldersScreen.swift

387 lines · 19473 bytes

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