Sources/Orgstar/Sidebar.swift

b50ce164c2ff8b87dcc4256e1b3c97994dc431f8
orgstar/Sources/Orgstar/Sidebar.swift

217 lines · 9587 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 {
 87                        workspace.showError(String(localized: "Couldn't Add Folder", comment: "Error alert title"), error.localizedDescription)
 88                    }
 89                }
 90            }
 91            return true
 92        } isTargeted: { dropTargeted = $0 }
 93        .overlay {
 94            if dropTargeted { RoundedRectangle(cornerRadius: 6).strokeBorder(Color.accentColor, lineWidth: 2).padding(2) }
 95        }
 96        .safeAreaInset(edge: .bottom, spacing: 0) {
 97            SidebarBar(showsAgenda: $showsAgenda) {
 98                Button("Add Folder…", systemImage: "plus", action: addFolder)
 99                    .help("Add a folder (⇧⌘O)")
100                Menu {
101                    ForEach(workspace.rootPaths, id: \.self) { root in
102                        Button((root as NSString).lastPathComponent) { removing = root }
103                    }
104                } label: {
105                    Label("Remove from Sidebar", systemImage: "minus")
106                }
107                .menuIndicator(.hidden)
108                .fixedSize()
109                .disabled(workspace.rootPaths.isEmpty)
110                .help("Remove a folder from the sidebar")
111            }
112            .labelStyle(.iconOnly)
113        }
114        .confirmationDialog(
115            "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
116            isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
117        ) {
118            Button("Remove") {
119                if let root = removing { try? workspace.removeRoot(path: root) }
120                removing = nil
121            }
122        } message: {
123            Text("The folder and its files stay on disk.")
124        }
125        .fileOperations(self)
126    }
127
128    @ViewBuilder
129    private func folderMenu(_ root: String) -> some View {
130        Button("New File…") { ask(.create(folder: root)) }
131        Divider()
132        Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
133        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
134        Divider()
135        Button("Remove from Sidebar…") { removing = root }
136    }
137
138    private func icon(_ node: FileTreeNode) -> String {
139        if node.isDownloading { return "icloud.and.arrow.down" }
140        guard let file = node.file else { return "folder" }
141        switch file.kind {
142        case .org: return "doc.text"
143        case .archive: return "archivebox"
144        case .conflict: return "exclamationmark.triangle"
145        case .other:
146            guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
147            if type.conforms(to: .image) { return "photo" }
148            if type.conforms(to: .pdf) { return "doc.richtext" }
149            if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
150            if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
151            if type.conforms(to: .text) { return "doc.plaintext" }
152            return "doc"
153        }
154    }
155}
156
157/// The bar under the sidebar: what the shown side offers, then the button that switches between
158/// the files and the agenda.
159struct SidebarBar<Content: View>: View {
160    @Binding var showsAgenda: Bool
161    @ViewBuilder var content: Content
162    @Environment(\.orgTheme) private var theme
163    @Environment(\.colorScheme) private var colorScheme
164
165    var body: some View {
166        HStack(spacing: 6) {
167            content
168            Spacer()
169            Button(showsAgenda ? "Show Files" : "Show Agenda", systemImage: showsAgenda ? "folder" : "calendar") { showsAgenda.toggle() }
170                .labelStyle(.iconOnly)
171                .help(showsAgenda ? "Show the files" : "Show the agenda")
172        }
173        .buttonStyle(.borderless)
174        .menuStyle(.borderlessButton)
175        .font(.system(size: 14, weight: .medium))
176        .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
177        .padding(.horizontal, 10)
178        .padding(.vertical, 7)
179        // Solid, so the rows scrolling under the bar don't show through its buttons.
180        .background {
181            if let color = theme.color("sidebar-background", in: colorScheme) {
182                color
183            } else {
184                Rectangle().fill(.ultraThickMaterial)
185            }
186        }
187        .overlay(alignment: .top) { Divider() }
188    }
189}
190
191struct OutlineColumn: View {
192    let session: DocumentSession
193    @Environment(\.orgTheme) private var theme
194    @Environment(\.colorScheme) private var colorScheme
195
196    var body: some View {
197        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
198            Button {
199                session.reveal(entry.start)
200            } label: {
201                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
202                    .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
203                    .lineLimit(1)
204                    .padding(.leading, CGFloat(entry.level - 1) * 12)
205            }
206            .buttonStyle(.plain)
207        }
208        .themedListBackground(theme.color("sidebar-background", in: colorScheme))
209        .overlay {
210            if session.path != nil, !session.isOrg {
211                ContentUnavailableView("No Outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
212            } else if session.path != nil, session.outline.isEmpty {
213                ContentUnavailableView("No Headings", systemImage: "list.bullet.indent")
214            }
215        }
216    }
217}
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