Sources/OrgstarMobile/FoldersScreen.swift

89cd390831f813d3a7b29905803e98849b457be9
orgstar/Sources/OrgstarMobile/FoldersScreen.swift

386 lines · 19343 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    /// 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        RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { [] }, show: { workspace.lastError = $0 }, ask: { $1(nil) },
166                    open: { path, offset in model.openRequest = .offset(path, offset) }, insertLink: { _, _ in },
167                    refresh: { Task { await workspace.refresh() } }).run(id)
168    }
169}
170
171/// A subfolder's own list, asking about its own changes; an added folder's, from the iPad's
172/// sidebar.
173struct FolderPage: View {
174    let workspace: WorkspaceModel
175    let session: DocumentSession
176    let route: FolderRoute
177    @State private var deleting: String?
178    @State private var changes = 0
179    @State private var creating: NewItem?
180    @State private var templating: TemplateFolder?
181
182    var body: some View {
183        let folder = route.folder.isEmpty ? route.root : route.root + "/" + route.folder
184        List { FolderContents(workspace: workspace, root: route.root, folder: route.folder, deleting: $deleting, changes: changes) }
185            .navigationTitle(((route.folder.isEmpty ? route.root : route.folder) as NSString).lastPathComponent)
186            .confirmDeletion($deleting, workspace: workspace, session: session) { changes += 1 }
187            .createItem($creating, workspace: workspace) { changes += 1 }
188            .newFromTemplate($templating, workspace: workspace, session: session)
189            .toolbar {
190                ToolbarItem(placement: .primaryAction) {
191                    Menu("New", systemImage: "plus") {
192                        Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) }
193                        Button("New File from Template…", systemImage: "doc.on.doc") { templating = TemplateFolder(path: folder) }
194                        Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) }
195                    }
196                }
197            }
198    }
199}
200
201/// A file or folder to create in `folder`, named in an alert.
202private struct NewItem: Identifiable {
203    let folder: String
204    let isFolder: Bool
205    var id: String { folder + (isFolder ? "/" : "") }
206}
207
208/// The alert naming a new file or folder.
209private struct NewItemAlert: ViewModifier {
210    @Binding var creating: NewItem?
211    let workspace: WorkspaceModel
212    let created: () -> Void
213    @State private var name = ""
214
215    func body(content: Content) -> some View {
216        content.alert(creating?.isFolder == true ? "New Folder" : "New File", isPresented: Binding { creating != nil } set: { if !$0 { creating = nil } }) {
217            TextField("Name", text: $name)
218                .autocorrectionDisabled()
219                .textInputAutocapitalization(.never)
220            Button("Create") {
221                guard let item = creating else { return }
222                let typed = name
223                name = ""
224                Task {
225                    do {
226                        if item.isFolder { try Self.makeFolder(typed, in: item.folder) } else { _ = try await workspace.createFile(named: typed, in: item.folder) }
227                        created()
228                    } catch {
229                        workspace.showError(item.isFolder ? String(localized: "Couldn't Create Folder", comment: "Error alert title")
230                                            : String(localized: "Couldn't Create File", comment: "Error alert title"), error.localizedDescription)
231                    }
232                }
233            }
234            Button("Cancel", role: .cancel) { name = "" }
235        } message: {
236            if creating?.isFolder != true { Text("A name without an extension gets .org.") }
237        }
238    }
239
240    static func makeFolder(_ name: String, in folder: String) throws {
241        let trimmed = name.trimmingCharacters(in: .whitespaces)
242        guard !trimmed.isEmpty, !trimmed.contains("/"), !trimmed.hasPrefix(".") else {
243            throw WorkspaceModel.FileError(message: "Not a folder name: \(name)")
244        }
245        let url = URL(fileURLWithPath: folder).appendingPathComponent(trimmed)
246        guard !FileManager.default.fileExists(atPath: url.path) else { throw WorkspaceModel.FileError(message: "\(trimmed) already exists.") }
247        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
248    }
249}
250
251private extension View {
252    func createItem(_ creating: Binding<NewItem?>, workspace: WorkspaceModel, created: @escaping () -> Void) -> some View {
253        modifier(NewItemAlert(creating: creating, workspace: workspace, created: created))
254    }
255
256    /// Asks before deleting the file or empty folder in `deleting`, closing a file first.
257    func confirmDeletion(_ deleting: Binding<String?>, workspace: WorkspaceModel, session: DocumentSession, deleted: @escaping () -> Void) -> some View {
258        let name = deleting.wrappedValue.map { ($0 as NSString).lastPathComponent } ?? ""
259        var isFolder: ObjCBool = false
260        let folder = deleting.wrappedValue.map { FileManager.default.fileExists(atPath: $0, isDirectory: &isFolder) && isFolder.boolValue } ?? false
261        return confirmationDialog("Delete “\(name)”?", isPresented: Binding { deleting.wrappedValue != nil } set: { if !$0 { deleting.wrappedValue = nil } },
262                                  titleVisibility: .visible) {
263            Button("Delete", role: .destructive) {
264                guard let path = deleting.wrappedValue else { return }
265                deleting.wrappedValue = nil
266                session.kill(path)
267                Task {
268                    do { try await workspace.trash(path) } catch {
269                        workspace.showError(folder ? String(localized: "Couldn't Delete Folder", comment: "Error alert title")
270                                            : String(localized: "Couldn't Delete File", comment: "Error alert title"), error.localizedDescription)
271                    }
272                    deleted()
273                }
274            }
275        } message: {
276            Text(folder ? "The empty folder is removed." : "The whole file is removed. Files in iCloud Drive go to Recently Deleted in the Files app.")
277        }
278    }
279}
280
281extension FoldersScreen {
282    @ViewBuilder
283    private func newItems(in folder: String) -> some View {
284        Button("New File…", systemImage: "doc.badge.plus") { creating = NewItem(folder: folder, isFolder: false) }
285        Button("New File from Template…", systemImage: "doc.on.doc") { templating = TemplateFolder(path: folder) }
286        Button("New Folder…", systemImage: "folder.badge.plus") { creating = NewItem(folder: folder, isFolder: true) }
287    }
288}
289
290/// A folder with nothing in it but dotfiles.
291private func isEmptyFolder(_ path: String) -> Bool {
292    guard let inside = try? FileManager.default.contentsOfDirectory(atPath: path) else { return false }
293    return inside.allSatisfy { $0.hasPrefix(".") }
294}
295
296/// A subfolder to show, relative to its root.
297struct FolderRoute: Hashable {
298    let root: String
299    let folder: String
300}
301
302/// One folder's subfolders, which open their own contents, then its org files and the files
303/// still downloading into it. `folder` is relative to `root`, empty for the root itself.
304private struct FolderContents: View {
305    let workspace: WorkspaceModel
306    let root: String
307    let folder: String
308    @Binding var deleting: String?
309    /// Changes after each deletion, which the index may not show, so empty folders are read again.
310    let changes: Int
311    /// Files not yet downloaded that were tapped, shown with a spinner until they arrive.
312    @State private var requested: Set<String> = []
313
314    private var prefix: String { folder.isEmpty ? "" : folder + "/" }
315
316    /// Subfolders on disk with nothing in them but dotfiles, which the index, built from
317    /// files, doesn't know of.
318    private func emptySubfolders() -> [String] {
319        let fm = FileManager.default
320        let url = URL(fileURLWithPath: root).appendingPathComponent(folder)
321        guard let names = try? fm.contentsOfDirectory(atPath: url.path) else { return [] }
322        return names.filter { name in
323            var isFolder: ObjCBool = false
324            let path = url.appendingPathComponent(name).path
325            return !name.hasPrefix(".") && fm.fileExists(atPath: path, isDirectory: &isFolder) && isFolder.boolValue && isEmptyFolder(path)
326        }
327    }
328
329    /// Paths below this folder, relative to it.
330    private func below(_ relativePaths: [String]) -> [String] {
331        relativePaths.filter { $0.hasPrefix(prefix) }.map { String($0.dropFirst(prefix.count)) }
332    }
333
334    var body: some View {
335        let files = workspace.files.filter { $0.root == root && ($0.kind == .org || DocumentSession.isEncryptedOrgFile($0.path)) && $0.relativePath.hasPrefix(prefix) }
336        let pending = below(workspace.downloading.filter { $0.hasPrefix(root + "/") }.map { String($0.dropFirst(root.count + 1)) })
337        let empty = Set(emptySubfolders())
338        let subfolders = Set((below(files.map(\.relativePath)) + pending).compactMap { path in
339            path.firstIndex(of: "/").map { String(path[..<$0]) }
340        }).union(empty).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
341        ForEach(subfolders, id: \.self) { name in
342            // A value, as the files' links are: a stack mixing the two kinds pushes wrongly.
343            NavigationLink(value: FolderRoute(root: root, folder: prefix + name)) {
344                Label(name, systemImage: "folder")
345            }
346            .swipeActions(edge: .trailing) {
347                if empty.contains(name) {
348                    Button("Delete", systemImage: "trash") { deleting = root + "/" + prefix + name }.tint(.red)
349                }
350            }
351            .contextMenu {
352                if empty.contains(name) {
353                    Button("Delete…", systemImage: "trash", role: .destructive) { deleting = root + "/" + prefix + name }
354                }
355            }
356        }
357        ForEach(files.filter { !$0.relativePath.dropFirst(prefix.count).contains("/") }) { file in
358            NavigationLink(value: ReaderRoute.file(file.path)) {
359                Label(file.name, systemImage: "doc.text")
360            }
361            .swipeActions(edge: .trailing) {
362                Button("Delete", systemImage: "trash") { deleting = file.path }.tint(.red)
363            }
364            .contextMenu {
365                Button("Delete…", systemImage: "trash", role: .destructive) { deleting = file.path }
366            }
367        }
368        ForEach(pending.filter { !$0.contains("/") }, id: \.self) { name in
369            let path = root + "/" + prefix + name
370            Button {
371                // iCloud downloads these by itself in time; a tap asks for this one now.
372                try? FileManager.default.startDownloadingUbiquitousItem(at: URL(fileURLWithPath: path))
373                requested.insert(path)
374            } label: {
375                HStack {
376                    Label(name, systemImage: "icloud.and.arrow.down")
377                    Spacer()
378                    if requested.contains(path) { ProgressView() }
379                }
380                .foregroundStyle(.secondary)
381            }
382            .accessibilityHint(requested.contains(path) ? Text("Downloading") : Text("Downloads the file from iCloud"))
383        }
384    }
385}
386#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