Sources/Orgstar/Sidebar.swift

73fcba4bfb8709ee26c1b1ecee1b70ce400e5b7e
orgstar/Sources/Orgstar/Sidebar.swift

219 lines · 9687 bytes

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