Sources/Orgstar/Sidebar.swift
218 lines · 9610 bytes
6 symbols in this file
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 .other:
147 guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
148 if type.conforms(to: .image) { return "photo" }
149 if type.conforms(to: .pdf) { return "doc.richtext" }
150 if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
151 if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
152 if type.conforms(to: .text) { return "doc.plaintext" }
153 return "doc"
154 }
155 }
156}
157
158/// The bar under the sidebar: what the shown side offers, then the button that switches between
159/// the files and the agenda.
160struct SidebarBar<Content: View>: View {
161 @Binding var showsAgenda: Bool
162 @ViewBuilder var content: Content
163 @Environment(\.orgTheme) private var theme
164 @Environment(\.colorScheme) private var colorScheme
165
166 var body: some View {
167 HStack(spacing: 6) {
168 content
169 Spacer()
170 Button(showsAgenda ? "Show Files" : "Show Agenda", systemImage: showsAgenda ? "folder" : "calendar") { showsAgenda.toggle() }
171 .labelStyle(.iconOnly)
172 .help(showsAgenda ? "Show the files" : "Show the agenda")
173 }
174 .buttonStyle(.borderless)
175 .menuStyle(.borderlessButton)
176 .font(.system(size: 14, weight: .medium))
177 .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
178 .padding(.horizontal, 10)
179 .padding(.vertical, 7)
180 // Solid, so the rows scrolling under the bar don't show through its buttons.
181 .background {
182 if let color = theme.color("sidebar-background", in: colorScheme) {
183 color
184 } else {
185 Rectangle().fill(.ultraThickMaterial)
186 }
187 }
188 .overlay(alignment: .top) { Divider() }
189 }
190}
191
192struct OutlineColumn: View {
193 let session: DocumentSession
194 @Environment(\.orgTheme) private var theme
195 @Environment(\.colorScheme) private var colorScheme
196
197 var body: some View {
198 List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
199 Button {
200 session.reveal(entry.start)
201 } label: {
202 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
203 .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
204 .lineLimit(1)
205 .padding(.leading, CGFloat(entry.level - 1) * 12)
206 }
207 .buttonStyle(.plain)
208 }
209 .themedListBackground(theme.color("sidebar-background", in: colorScheme))
210 .overlay {
211 if session.path != nil, !session.isOrg {
212 ContentUnavailableView("No Outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
213 } else if session.path != nil, session.outline.isEmpty {
214 ContentUnavailableView("No Headings", systemImage: "list.bullet.indent")
215 }
216 }
217 }
218}