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