Sources/Orgstar/SidebarFiles.swift

427abbbee0d20a70754de8e0e0846dae001f9c92
orgstar/Sources/Orgstar/SidebarFiles.swift history · blame · raw

113 lines · 4630 bytes

  1import AppKit
  2import OrgApp
  3import SwiftUI
  4
  5/// Creating, renaming and trashing files from the sidebar.
  6enum FileOperation: Equatable {
  7    case create(folder: String)
  8    case rename(path: String)
  9    case trash(path: String)
 10}
 11
 12extension Sidebar {
 13    @ViewBuilder
 14    func fileMenu(_ node: FileTreeNode) -> some View {
 15        let folder = node.file == nil ? node.path : (node.path as NSString).deletingLastPathComponent
 16        Button("New File…") { ask(.create(folder: folder)) }
 17        Divider()
 18        Button("Rename…") { ask(.rename(path: node.path)) }
 19        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: node.path)]) }
 20        Divider()
 21        Button("Move to Trash…") { ask(.trash(path: node.path)) }
 22    }
 23
 24    func ask(_ operation: FileOperation) {
 25        switch operation {
 26        case .create: name = ""
 27        case .rename(let path): name = (path as NSString).lastPathComponent
 28        case .trash: break
 29        }
 30        pending = operation
 31    }
 32
 33    /// Whether `path` is the open file or a folder holding it.
 34    func holdsOpenFile(_ path: String) -> Bool {
 35        guard let open = session.path else { return false }
 36        return open == path || open.hasPrefix(path + "/")
 37    }
 38
 39    func finish() {
 40        guard let operation = pending else { return }
 41        pending = nil
 42        Task {
 43            do {
 44                switch operation {
 45                case .create(let folder):
 46                    selection = try await workspace.createFile(named: name, in: folder)
 47                case .rename(let path):
 48                    let affected = holdsOpenFile(path)
 49                    // The open file is saved first, so the rename carries its edits.
 50                    if affected, !UnsavedChanges.resolve(session) { return }
 51                    let renamed = try await workspace.rename(path, to: name)
 52                    if affected, let open = session.path {
 53                        let moved = renamed + open.dropFirst(path.count)
 54                        session.open(moved)
 55                        selection = moved
 56                    }
 57                case .trash(let path):
 58                    if holdsOpenFile(path) {
 59                        session.close()
 60                        selection = nil
 61                    }
 62                    try await workspace.trash(path)
 63                }
 64            } catch {
 65                failure = error.localizedDescription
 66            }
 67        }
 68    }
 69}
 70
 71extension View {
 72    func fileOperations(_ sidebar: Sidebar) -> some View {
 73        let names: Binding<String> = sidebar.$name
 74        return self
 75            .alert(title(sidebar.pending), isPresented: Binding { sidebar.pending?.needsName == true } set: { if !$0 { sidebar.pending = nil } }) {
 76                TextField("Name", text: names)
 77                Button(sidebar.pending.map { if case .create = $0 { "Create" } else { "Rename" } } ?? "OK") { sidebar.finish() }
 78                Button("Cancel", role: .cancel) { sidebar.pending = nil }
 79            } message: {
 80                if case .create = sidebar.pending { Text("A name without an extension gets .org. Use folder/name to make folders.") }
 81            }
 82            .confirmationDialog(title(sidebar.pending), isPresented: Binding { sidebar.pending?.needsName == false } set: { if !$0 { sidebar.pending = nil } }) {
 83                Button("Move to Trash", role: .destructive) { sidebar.finish() }
 84            } message: {
 85                if case .trash(let path) = sidebar.pending, sidebar.holdsOpenFile(path), sidebar.session.isDirty {
 86                    Text("Unsaved changes to the open file will be lost.")
 87                } else {
 88                    Text("You can put it back from the Trash in Finder.")
 89                }
 90            }
 91            .alert("Couldn't change the file", isPresented: Binding { sidebar.failure != nil } set: { if !$0 { sidebar.failure = nil } }) {
 92                Button("OK") { sidebar.failure = nil }
 93            } message: {
 94                Text(sidebar.failure ?? "")
 95            }
 96    }
 97
 98    private func title(_ operation: FileOperation?) -> String {
 99        switch operation {
100        case .create(let folder): "New file in “\((folder as NSString).lastPathComponent)”"
101        case .rename(let path): "Rename “\((path as NSString).lastPathComponent)”"
102        case .trash(let path): "Move “\((path as NSString).lastPathComponent)” to the Trash?"
103        case nil: ""
104        }
105    }
106}
107
108extension FileOperation {
109    var needsName: Bool {
110        if case .trash = self { return false }
111        return true
112    }
113}