Sources/Orgstar/Sidebar.swift

design-themes-widgets
orgstar/Sources/Orgstar/Sidebar.swift history · blame · raw

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