Sources/Orgstar/ContentView.swift

923f63b7fcb447d5753267b1cf81e58da6449ee6
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

197 lines · 7043 bytes

  1import OrgApp
  2import OrgIndex
  3import SwiftUI
  4
  5struct ContentView: View {
  6    let workspace: WorkspaceModel
  7    @Bindable var commands: AppCommands
  8    @State private var session = DocumentSession()
  9    @State private var selectedFile: String?
 10    @State private var query = ""
 11    @FocusState private var searchFocused: Bool
 12
 13    var body: some View {
 14        NavigationSplitView {
 15            Sidebar(workspace: workspace, selection: $selectedFile)
 16                .navigationSplitViewColumnWidth(min: 200, ideal: 260)
 17        } content: {
 18            Group {
 19                if query.isEmpty {
 20                    OutlineColumn(session: session)
 21                } else {
 22                    SearchResults(results: workspace.search(query)) { location in
 23                        selectedFile = location.path
 24                        session.show(location)
 25                    }
 26                }
 27            }
 28            .navigationSplitViewColumnWidth(min: 160, ideal: 220, max: 360)
 29        } detail: {
 30            if session.path != nil {
 31                EditorView(session: session)
 32            } else {
 33                ContentUnavailableView(
 34                    workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
 35                    systemImage: "doc.text",
 36                    description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
 37                )
 38            }
 39        }
 40        .navigationTitle(session.path.map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
 41        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
 42        .searchFocused($searchFocused)
 43        .toolbar {
 44            if workspace.isIndexing { ProgressView().controlSize(.small) }
 45        }
 46        .onChange(of: selectedFile) { _, path in
 47            if let path, path != session.path { session.open(path) }
 48        }
 49        .onChange(of: workspace.changedFile?.version) {
 50            if let path = workspace.changedFile?.path { session.fileChanged(path) }
 51        }
 52        .onChange(of: commands.focusSearch) { _, focus in
 53            if focus {
 54                searchFocused = true
 55                commands.focusSearch = false
 56            }
 57        }
 58        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
 59            guard case .success(let url) = result else { return }
 60            Task {
 61                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
 62            }
 63        }
 64        .sheet(isPresented: $commands.showingQuickOpen) {
 65            QuickOpenView(workspace: workspace) { entry in
 66                selectedFile = entry.path
 67                commands.showingQuickOpen = false
 68            }
 69        }
 70        .alert("Orgstar", isPresented: errorShown) {
 71            Button("OK") {
 72                workspace.lastError = nil
 73                session.lastError = nil
 74            }
 75        } message: {
 76            Text(workspace.lastError ?? session.lastError ?? "")
 77        }
 78        .task {
 79            DevelopmentHooks.scheduleSnapshot()
 80            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
 81            await workspace.refresh()
 82            workspace.startWatching()
 83        }
 84    }
 85
 86    private var errorShown: Binding<Bool> {
 87        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
 88    }
 89}
 90
 91struct Sidebar: View {
 92    let workspace: WorkspaceModel
 93    @Binding var selection: String?
 94
 95    var body: some View {
 96        List(selection: $selection) {
 97            ForEach(workspace.rootPaths, id: \.self) { root in
 98                Section((root as NSString).lastPathComponent) {
 99                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
100                        Label(node.name, systemImage: icon(node))
101                            .foregroundStyle(node.file?.kind == .conflict ? .orange : .primary)
102                            .tag(node.file?.path)
103                    }
104                }
105                .contextMenu {
106                    Button("Remove Folder") { try? workspace.removeRoot(path: root) }
107                }
108            }
109        }
110        .listStyle(.sidebar)
111    }
112
113    private func icon(_ node: FileTreeNode) -> String {
114        guard let file = node.file else { return "folder" }
115        switch file.kind {
116        case .org: return "doc.text"
117        case .archive: return "archivebox"
118        case .conflict: return "exclamationmark.triangle"
119        }
120    }
121}
122
123struct OutlineColumn: View {
124    let session: DocumentSession
125
126    var body: some View {
127        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
128            Button {
129                session.reveal(entry.start)
130            } label: {
131                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
132                    .lineLimit(1)
133                    .padding(.leading, CGFloat(entry.level - 1) * 12)
134            }
135            .buttonStyle(.plain)
136        }
137        .overlay {
138            if session.path != nil, session.outline.isEmpty {
139                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
140            }
141        }
142    }
143}
144
145struct SearchResults: View {
146    let results: [HeadingLocation]
147    let open: (HeadingLocation) -> Void
148
149    var body: some View {
150        List(results, id: \.self) { location in
151            Button {
152                open(location)
153            } label: {
154                VStack(alignment: .leading, spacing: 2) {
155                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
156                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
157                }
158            }
159            .buttonStyle(.plain)
160        }
161        .overlay {
162            if results.isEmpty { ContentUnavailableView.search }
163        }
164    }
165}
166
167struct QuickOpenView: View {
168    let workspace: WorkspaceModel
169    let open: (FileEntry) -> Void
170    @State private var query = ""
171    @Environment(\.dismiss) private var dismiss
172
173    var body: some View {
174        let matches = workspace.quickOpen(query)
175        VStack(spacing: 0) {
176            TextField("Open file", text: $query)
177                .textFieldStyle(.plain)
178                .font(.title3)
179                .padding(12)
180                .onSubmit { if let first = matches.first { open(first) } }
181            Divider()
182            List(matches) { entry in
183                Button {
184                    open(entry)
185                } label: {
186                    VStack(alignment: .leading, spacing: 2) {
187                        Text(entry.name)
188                        Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
189                    }
190                }
191                .buttonStyle(.plain)
192            }
193        }
194        .frame(width: 520, height: 360)
195        .onExitCommand { dismiss() }
196    }
197}