Sources/Orgstar/Sidebar.swift

147 lines · 6313 bytes

  1import OrgApp
  2import OrgCore
  3import OrgWorkspace
  4import SwiftUI
  5import UniformTypeIdentifiers
  6
  7struct Sidebar: View {
  8    let workspace: WorkspaceModel
  9    let session: DocumentSession
 10    @Binding var selection: String?
 11    var addFolder: () -> Void = {}
 12    /// Folders shown collapsed, by path, one per line.
 13    @AppStorage("collapsedFolders") private var collapsedText = ""
 14    @State private var removing: String?
 15    /// A file operation waiting for a name or a confirmation.
 16    @Environment(\.orgTheme) private var theme
 17    @Environment(\.colorScheme) private var colorScheme
 18    @State var pending: FileOperation?
 19    @State var name = ""
 20    @State var failure: String?
 21
 22    private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) }
 23
 24    private func expanded(_ root: String) -> Binding<Bool> {
 25        Binding {
 26            !collapsed.contains(root)
 27        } set: { isExpanded in
 28            var set = collapsed
 29            if isExpanded { set.remove(root) } else { set.insert(root) }
 30            collapsedText = set.sorted().joined(separator: "\n")
 31        }
 32    }
 33
 34    var body: some View {
 35        List(selection: $selection) {
 36            ForEach(workspace.rootPaths, id: \.self) { root in
 37                Section(isExpanded: expanded(root)) {
 38                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
 39                        Label(node.name, systemImage: icon(node))
 40                            .foregroundStyle(node.file?.kind == .conflict ? .orange : node.isDownloading ? .secondary : theme.color("sidebar-foreground") ?? .primary)
 41                            .help(node.isDownloading ? "Downloading from iCloud" : "")
 42                            .tag(node.file?.path)
 43                            .contextMenu { fileMenu(node) }
 44                    }
 45                } header: {
 46                    Text((root as NSString).lastPathComponent)
 47                        .foregroundStyle(theme.color("sidebar-header") ?? .secondary)
 48                        .help(root)
 49                        .contextMenu { folderMenu(root) }
 50                }
 51            }
 52        }
 53        .listStyle(.sidebar)
 54        .themedListBackground(theme.color("sidebar-background", in: colorScheme))
 55        .safeAreaInset(edge: .bottom, spacing: 0) {
 56            HStack(spacing: 4) {
 57                Button("Add Folder…", systemImage: "plus", action: addFolder)
 58                    .help("Add a folder (⇧⌘O)")
 59                Menu {
 60                    ForEach(workspace.rootPaths, id: \.self) { root in
 61                        Button((root as NSString).lastPathComponent) { removing = root }
 62                    }
 63                } label: {
 64                    Label("Remove Folder", systemImage: "minus")
 65                }
 66                .menuIndicator(.hidden)
 67                .fixedSize()
 68                .disabled(workspace.rootPaths.isEmpty)
 69                .help("Remove a folder from the sidebar")
 70                Spacer()
 71            }
 72            .labelStyle(.iconOnly)
 73            .buttonStyle(.borderless)
 74            .menuStyle(.borderlessButton)
 75            .padding(.horizontal, 10)
 76            .padding(.vertical, 6)
 77        }
 78        .confirmationDialog(
 79            "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
 80            isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
 81        ) {
 82            Button("Remove") {
 83                if let root = removing { try? workspace.removeRoot(path: root) }
 84                removing = nil
 85            }
 86        } message: {
 87            Text("The folder and its files stay on disk.")
 88        }
 89        .fileOperations(self)
 90    }
 91
 92    @ViewBuilder
 93    private func folderMenu(_ root: String) -> some View {
 94        Button("New File…") { ask(.create(folder: root)) }
 95        Divider()
 96        Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
 97        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
 98        Divider()
 99        Button("Remove from Sidebar…") { removing = root }
100    }
101
102    private func icon(_ node: FileTreeNode) -> String {
103        if node.isDownloading { return "icloud.and.arrow.down" }
104        guard let file = node.file else { return "folder" }
105        switch file.kind {
106        case .org: return "doc.text"
107        case .archive: return "archivebox"
108        case .conflict: return "exclamationmark.triangle"
109        case .other:
110            guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
111            if type.conforms(to: .image) { return "photo" }
112            if type.conforms(to: .pdf) { return "doc.richtext" }
113            if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
114            if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
115            if type.conforms(to: .text) { return "doc.plaintext" }
116            return "doc"
117        }
118    }
119}
120
121struct OutlineColumn: View {
122    let session: DocumentSession
123    @Environment(\.orgTheme) private var theme
124    @Environment(\.colorScheme) private var colorScheme
125
126    var body: some View {
127        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
128            Button {
129                session.reveal(entry.start)
130            } label: {
131                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
132                    .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
133                    .lineLimit(1)
134                    .padding(.leading, CGFloat(entry.level - 1) * 12)
135            }
136            .buttonStyle(.plain)
137        }
138        .themedListBackground(theme.color("sidebar-background", in: colorScheme))
139        .overlay {
140            if session.path != nil, !session.isOrg {
141                ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
142            } else if session.path != nil, session.outline.isEmpty {
143                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
144            }
145        }
146    }
147}