Sources/Orgstar/ContentView.swift

b0ca506efd9515fa52a92b52fea3c28a8e55e708
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

277 lines · 11427 bytes

  1import OrgApp
  2import OrgCore
  3import OrgEditorAppKit
  4import OrgIndex
  5import SwiftUI
  6
  7struct ContentView: View {
  8    let workspace: WorkspaceModel
  9    let session: DocumentSession
 10    @Bindable var commands: AppCommands
 11    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 12    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 13    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 14    @State private var keymap = KeymapPreset.emacs.keymap
 15    @AppStorage("tagsColumn") private var tagsColumn = -77
 16    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
 17    @AppStorage("splitLine") private var splitLine = false
 18    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 19    @AppStorage("fillColumn") private var fillColumn = 80
 20
 21    private var options: EditingOptions {
 22        Preferences.options(tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists, fillColumn: fillColumn)
 23    }
 24    @State private var selectedFile: String?
 25    @State private var query = ""
 26    @FocusState private var searchFocused: Bool
 27
 28    var body: some View {
 29        NavigationSplitView {
 30            Sidebar(workspace: workspace, selection: $selectedFile)
 31                .navigationSplitViewColumnWidth(min: 200, ideal: 260)
 32        } content: {
 33            Group {
 34                if query.isEmpty {
 35                    OutlineColumn(session: session)
 36                } else {
 37                    SearchResults(results: workspace.search(query, overlay: workspace.overlay(path: session.path, document: session.document))) { location in
 38                        guard location.path == session.path || UnsavedChanges.resolve(session) else { return }
 39                        selectedFile = location.path
 40                        session.show(location)
 41                    }
 42                }
 43            }
 44            .navigationSplitViewColumnWidth(min: 160, ideal: 220, max: 360)
 45        } detail: {
 46            if session.path != nil {
 47                EditorView(session: session, commands: commands, keymap: keymap, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, onAppCommand: perform)
 48                    .safeAreaInset(edge: .bottom, spacing: 0) { EchoArea(commands: commands) }
 49            } else {
 50                ContentUnavailableView(
 51                    workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
 52                    systemImage: "doc.text",
 53                    description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
 54                )
 55            }
 56        }
 57        .navigationTitle(session.path.map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
 58        .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
 59        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
 60        .searchFocused($searchFocused)
 61        .toolbar {
 62            if workspace.isIndexing { ProgressView().controlSize(.small) }
 63            if session.conflict != nil {
 64                Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
 65                    .help("The file changed on disk, and the changes conflict with yours")
 66            }
 67        }
 68        .onChange(of: selectedFile) { old, path in
 69            guard let path, path != session.path else { return }
 70            if UnsavedChanges.resolve(session) {
 71                session.open(path)
 72            } else {
 73                selectedFile = old
 74            }
 75        }
 76        .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
 77        .onChange(of: options, initial: true) { _, options in session.options = options }
 78        .onChange(of: preset, initial: true) { loadKeymap() }
 79        .sheet(isPresented: $commands.showingPalette) {
 80            PaletteView(keymap: keymap) { id in
 81                commands.showingPalette = false
 82                // After the sheet closes, so app commands can present their own.
 83                DispatchQueue.main.async { perform(id) }
 84            }
 85        }
 86        .onChange(of: session.conflict) { _, conflict in
 87            if conflict != nil { commands.showingConflict = true }
 88        }
 89        .alert("Conflicting changes", isPresented: $commands.showingConflict) {
 90            Button("Keep Mine") { session.keepMine() }
 91            Button("Use Disk Version") { session.useDiskVersion() }
 92            Button("Decide Later", role: .cancel) {}
 93        } message: {
 94            Text((session.conflict ?? "") + " The version you don't keep is saved in the recovery folder.")
 95        }
 96        .onChange(of: workspace.changedFile?.version) {
 97            if let path = workspace.changedFile?.path { session.fileChanged(path) }
 98        }
 99        .onChange(of: commands.focusSearch) { _, focus in
100            if focus {
101                searchFocused = true
102                commands.focusSearch = false
103            }
104        }
105        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
106            guard case .success(let url) = result else { return }
107            Task {
108                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
109            }
110        }
111        .sheet(isPresented: $commands.showingQuickOpen) {
112            QuickOpenView(workspace: workspace) { entry in
113                selectedFile = entry.path
114                commands.showingQuickOpen = false
115            }
116        }
117        .alert("Orgstar", isPresented: errorShown) {
118            Button("OK") {
119                workspace.lastError = nil
120                session.lastError = nil
121            }
122        } message: {
123            Text(workspace.lastError ?? session.lastError ?? "")
124        }
125        .task {
126            DevelopmentHooks.scheduleSnapshot()
127            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
128            await workspace.refresh()
129            workspace.startWatching()
130        }
131    }
132
133    private func loadKeymap() {
134        let loaded = KeymapLoader.load(preset)
135        keymap = loaded.keymap
136        if let first = loaded.problems.first {
137            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
138            commands.show("keymap.toml: \(first)\(more)")
139        }
140    }
141
142    /// Runs a command from a key, the palette or the Org menu.
143    private func perform(_ id: String) {
144        switch id {
145        case "app.save":
146            if !session.save(), session.conflict != nil { commands.showingConflict = true }
147        case "app.quick-open": commands.showingQuickOpen = true
148        case "app.palette": commands.showingPalette = true
149        case "app.search": commands.focusSearch = true
150        case "app.reload-keymap":
151            loadKeymap()
152            commands.show("Keymap reloaded")
153        case "app.refile":
154            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
155            commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
156                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
157                if let message = session.refile(to: target) { commands.show(message) }
158            }
159        case "app.archive":
160            if let message = session.archive() { commands.show(message) }
161        default:
162            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
163        }
164    }
165
166    private var errorShown: Binding<Bool> {
167        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
168    }
169}
170
171struct Sidebar: View {
172    let workspace: WorkspaceModel
173    @Binding var selection: String?
174
175    var body: some View {
176        List(selection: $selection) {
177            ForEach(workspace.rootPaths, id: \.self) { root in
178                Section((root as NSString).lastPathComponent) {
179                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
180                        Label(node.name, systemImage: icon(node))
181                            .foregroundStyle(node.file?.kind == .conflict ? .orange : .primary)
182                            .tag(node.file?.path)
183                    }
184                }
185                .contextMenu {
186                    Button("Remove Folder") { try? workspace.removeRoot(path: root) }
187                }
188            }
189        }
190        .listStyle(.sidebar)
191    }
192
193    private func icon(_ node: FileTreeNode) -> String {
194        guard let file = node.file else { return "folder" }
195        switch file.kind {
196        case .org: return "doc.text"
197        case .archive: return "archivebox"
198        case .conflict: return "exclamationmark.triangle"
199        }
200    }
201}
202
203struct OutlineColumn: View {
204    let session: DocumentSession
205
206    var body: some View {
207        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
208            Button {
209                session.reveal(entry.start)
210            } label: {
211                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
212                    .lineLimit(1)
213                    .padding(.leading, CGFloat(entry.level - 1) * 12)
214            }
215            .buttonStyle(.plain)
216        }
217        .overlay {
218            if session.path != nil, session.outline.isEmpty {
219                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
220            }
221        }
222    }
223}
224
225struct SearchResults: View {
226    let results: [HeadingLocation]
227    let open: (HeadingLocation) -> Void
228
229    var body: some View {
230        List(results, id: \.self) { location in
231            Button {
232                open(location)
233            } label: {
234                VStack(alignment: .leading, spacing: 2) {
235                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
236                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
237                }
238            }
239            .buttonStyle(.plain)
240        }
241        .overlay {
242            if results.isEmpty { ContentUnavailableView.search }
243        }
244    }
245}
246
247struct QuickOpenView: View {
248    let workspace: WorkspaceModel
249    let open: (FileEntry) -> Void
250    @State private var query = ""
251    @Environment(\.dismiss) private var dismiss
252
253    var body: some View {
254        let matches = workspace.quickOpen(query)
255        VStack(spacing: 0) {
256            TextField("Open file", text: $query)
257                .textFieldStyle(.plain)
258                .font(.title3)
259                .padding(12)
260                .onSubmit { if let first = matches.first { open(first) } }
261            Divider()
262            List(matches) { entry in
263                Button {
264                    open(entry)
265                } label: {
266                    VStack(alignment: .leading, spacing: 2) {
267                        Text(entry.name)
268                        Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
269                    }
270                }
271                .buttonStyle(.plain)
272            }
273        }
274        .frame(width: 520, height: 360)
275        .onExitCommand { dismiss() }
276    }
277}