Sources/Orgstar/Sidebar.swift

ab3a6a9d7eefda3b6399b764a309fffd25313ba3
orgstar/Sources/Orgstar/Sidebar.swift

215 lines · 9466 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    /// The sidebar shows the agenda in place of the files.
 12    @Binding var showsAgenda: Bool
 13    var addFolder: () -> Void = {}
 14    /// Folders shown collapsed, by path, one per line.
 15    @AppStorage("collapsedFolders") private var collapsedText = ""
 16    @State private var removing: String?
 17    /// A drag with a folder is over the sidebar.
 18    @State private var dropTargeted = false
 19    /// A file operation waiting for a name or a confirmation.
 20    @Environment(\.orgTheme) private var theme
 21    @Environment(\.colorScheme) private var colorScheme
 22    @State var pending: FileOperation?
 23    @State var name = ""
 24    @State var failure: String?
 25
 26    private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) }
 27
 28    private func expanded(_ root: String) -> Binding<Bool> {
 29        Binding {
 30            !collapsed.contains(root)
 31        } set: { isExpanded in
 32            var set = collapsed
 33            if isExpanded { set.remove(root) } else { set.insert(root) }
 34            collapsedText = set.sorted().joined(separator: "\n")
 35        }
 36    }
 37
 38    var body: some View {
 39        List(selection: $selection) {
 40            ForEach(workspace.rootPaths, id: \.self) { root in
 41                Section(isExpanded: expanded(root)) {
 42                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
 43                        Label(node.name, systemImage: icon(node))
 44                            .foregroundStyle(node.file?.kind == .conflict ? .orange : node.isDownloading ? .secondary : theme.color("sidebar-foreground") ?? .primary)
 45                            .help(node.isDownloading ? "Downloading from iCloud" : "")
 46                            .tag(node.file?.path)
 47                            .contextMenu { fileMenu(node) }
 48                    }
 49                } header: {
 50                    Text((root as NSString).lastPathComponent)
 51                        .foregroundStyle(theme.color("sidebar-header") ?? .secondary)
 52                        .help(root)
 53                        .contextMenu { folderMenu(root) }
 54                }
 55            }
 56            #if APPSTORE
 57            if !workspace.unresolvedRoots.isEmpty {
 58                Section("Can't Open") {
 59                    ForEach(workspace.unresolvedRoots, id: \.path) { root in
 60                        HStack {
 61                            Label((root.path as NSString).lastPathComponent, systemImage: "exclamationmark.triangle")
 62                                .foregroundStyle(.secondary)
 63                            Spacer()
 64                            Button("Grant Access…") { GrantAccess.regrant(root, workspace: workspace) }
 65                                .buttonStyle(.borderless)
 66                                .controlSize(.small)
 67                        }
 68                        .help(root.path)
 69                        .contextMenu {
 70                            Button("Grant Access…") { GrantAccess.regrant(root, workspace: workspace) }
 71                            Button("Remove from Sidebar…") { removing = root.path }
 72                        }
 73                    }
 74                }
 75            }
 76            #endif
 77        }
 78        .listStyle(.sidebar)
 79        .themedListBackground(theme.color("sidebar-background", in: colorScheme))
 80        // Folders dropped from the Finder are added as Add Folder… adds them.
 81        .dropDestination(for: URL.self) { urls, _ in
 82            let folders = urls.filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
 83            guard !folders.isEmpty else { return false }
 84            Task {
 85                for folder in folders {
 86                    do { try await workspace.addRoot(folder) } catch { workspace.lastError = error.localizedDescription }
 87                }
 88            }
 89            return true
 90        } isTargeted: { dropTargeted = $0 }
 91        .overlay {
 92            if dropTargeted { RoundedRectangle(cornerRadius: 6).strokeBorder(Color.accentColor, lineWidth: 2).padding(2) }
 93        }
 94        .safeAreaInset(edge: .bottom, spacing: 0) {
 95            SidebarBar(showsAgenda: $showsAgenda) {
 96                Button("Add Folder…", systemImage: "plus", action: addFolder)
 97                    .help("Add a folder (⇧⌘O)")
 98                Menu {
 99                    ForEach(workspace.rootPaths, id: \.self) { root in
100                        Button((root as NSString).lastPathComponent) { removing = root }
101                    }
102                } label: {
103                    Label("Remove Folder", systemImage: "minus")
104                }
105                .menuIndicator(.hidden)
106                .fixedSize()
107                .disabled(workspace.rootPaths.isEmpty)
108                .help("Remove a folder from the sidebar")
109            }
110            .labelStyle(.iconOnly)
111        }
112        .confirmationDialog(
113            "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
114            isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
115        ) {
116            Button("Remove") {
117                if let root = removing { try? workspace.removeRoot(path: root) }
118                removing = nil
119            }
120        } message: {
121            Text("The folder and its files stay on disk.")
122        }
123        .fileOperations(self)
124    }
125
126    @ViewBuilder
127    private func folderMenu(_ root: String) -> some View {
128        Button("New File…") { ask(.create(folder: root)) }
129        Divider()
130        Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
131        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
132        Divider()
133        Button("Remove from Sidebar…") { removing = root }
134    }
135
136    private func icon(_ node: FileTreeNode) -> String {
137        if node.isDownloading { return "icloud.and.arrow.down" }
138        guard let file = node.file else { return "folder" }
139        switch file.kind {
140        case .org: return "doc.text"
141        case .archive: return "archivebox"
142        case .conflict: return "exclamationmark.triangle"
143        case .other:
144            guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
145            if type.conforms(to: .image) { return "photo" }
146            if type.conforms(to: .pdf) { return "doc.richtext" }
147            if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
148            if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
149            if type.conforms(to: .text) { return "doc.plaintext" }
150            return "doc"
151        }
152    }
153}
154
155/// The bar under the sidebar: what the shown side offers, then the button that switches between
156/// the files and the agenda.
157struct SidebarBar<Content: View>: View {
158    @Binding var showsAgenda: Bool
159    @ViewBuilder var content: Content
160    @Environment(\.orgTheme) private var theme
161    @Environment(\.colorScheme) private var colorScheme
162
163    var body: some View {
164        HStack(spacing: 6) {
165            content
166            Spacer()
167            Button(showsAgenda ? "Show Files" : "Show Agenda", systemImage: showsAgenda ? "folder" : "calendar") { showsAgenda.toggle() }
168                .labelStyle(.iconOnly)
169                .help(showsAgenda ? "Show the files" : "Show the agenda")
170        }
171        .buttonStyle(.borderless)
172        .menuStyle(.borderlessButton)
173        .font(.system(size: 14, weight: .medium))
174        .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
175        .padding(.horizontal, 10)
176        .padding(.vertical, 7)
177        // Solid, so the rows scrolling under the bar don't show through its buttons.
178        .background {
179            if let color = theme.color("sidebar-background", in: colorScheme) {
180                color
181            } else {
182                Rectangle().fill(.ultraThickMaterial)
183            }
184        }
185        .overlay(alignment: .top) { Divider() }
186    }
187}
188
189struct OutlineColumn: View {
190    let session: DocumentSession
191    @Environment(\.orgTheme) private var theme
192    @Environment(\.colorScheme) private var colorScheme
193
194    var body: some View {
195        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
196            Button {
197                session.reveal(entry.start)
198            } label: {
199                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
200                    .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
201                    .lineLimit(1)
202                    .padding(.leading, CGFloat(entry.level - 1) * 12)
203            }
204            .buttonStyle(.plain)
205        }
206        .themedListBackground(theme.color("sidebar-background", in: colorScheme))
207        .overlay {
208            if session.path != nil, !session.isOrg {
209                ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
210            } else if session.path != nil, session.outline.isEmpty {
211                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
212            }
213        }
214    }
215}
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