Sources/Orgstar/ContentView.swift

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

670 lines · 29742 bytes

  1import AppKit
  2import OrgApp
  3import OrgCore
  4import OrgEditorAppKit
  5import OrgPresentation
  6import OrgIndex
  7import SwiftUI
  8import UniformTypeIdentifiers
  9
 10struct ContentView: View {
 11    let workspace: WorkspaceModel
 12    let session: DocumentSession
 13    @Bindable var commands: AppCommands
 14    let scheduler: ReminderScheduler?
 15    let clock: ClockModel
 16    @AppStorage("reminders") private var remindersEnabled = true
 17    @AppStorage("reminderLead") private var reminderLead = 12
 18    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
 19    @State private var reminderAgenda: AgendaModel?
 20    @State private var trust = TrustStore()
 21    @State private var hotKey: GlobalHotKey?
 22    @State private var statusItem: ClockStatusItem?
 23    @AppStorage("globalCapture") private var globalCapture = true
 24    @State private var hour = 0
 25    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 26    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 27    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 28    @State private var keymap = KeymapPreset.emacs.keymap
 29    @AppStorage("tagsColumn") private var tagsColumn = -77
 30    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
 31    @AppStorage("splitLine") private var splitLine = false
 32    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 33    @AppStorage("fillColumn") private var fillColumn = 80
 34    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 35    @AppStorage("prettyEntities") private var prettyEntities = true
 36
 37    private var options: EditingOptions {
 38        Preferences.options(
 39            tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
 40            fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities
 41        )
 42    }
 43    @State private var selectedFile: String?
 44    /// A file that isn't text, shown as a preview instead of the open document.
 45    @State private var previewPath: String?
 46    @AppStorage("outlineShown") private var orgOutlineShown = true
 47    @AppStorage("outlineWidth") private var outlineWidth = 220.0
 48    @AppStorage("showMarkup") private var showMarkup = false
 49    @AppStorage("showLineNumbers") private var showLineNumbers = true
 50    @AppStorage("themeFont") private var themeFont = ""
 51    @AppStorage("themeFontSize") private var themeFontSize = 13
 52    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
 53    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
 54
 55    /// The theme's colors from config.toml with the type settings.
 56    private var theme: ThemeSpec {
 57        var spec = ConfigSync.shared.theme
 58        spec.font = themeFont
 59        spec.fontSize = themeFontSize
 60        spec.lineSpacing = themeLineSpacing
 61        spec.headingSizeStep = themeHeadingStep
 62        return spec
 63    }
 64    /// The outline for a file that isn't org, off until asked for.
 65    @State private var plainOutlineShown = false
 66    @State private var showingImport = false
 67    @State private var query = ""
 68    @FocusState private var searchFocused: Bool
 69    @Environment(\.openWindow) private var openWindow
 70    @Environment(\.openSettings) private var openSettings
 71
 72    /// Whether the outline pane shows: remembered for org files, hidden by default for
 73    /// other files, and always shown while search results are up.
 74    private var outlineShown: Bool {
 75        !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
 76    }
 77
 78    private func toggleOutline() {
 79        if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
 80    }
 81
 82    @ViewBuilder
 83    private var detail: some View {
 84        if let previewPath {
 85            FilePreview(path: previewPath)
 86        } else if session.path != nil {
 87            EditorView(session: session, commands: commands, keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers, theme: theme, onAppCommand: perform, onExternal: runExternal)
 88                .safeAreaInset(edge: .bottom, spacing: 0) {
 89                    VStack(spacing: 0) {
 90                        ModeLine(session: session, commands: commands, clock: clock, perform: perform)
 91                        EchoArea(commands: commands)
 92                    }
 93                }
 94        } else {
 95            ContentUnavailableView(
 96                workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
 97                systemImage: "doc.text",
 98                description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
 99            )
100        }
101    }
102
103    @ToolbarContentBuilder
104    private var toolbarItems: some ToolbarContent {
105        ToolbarItem(placement: .navigation) {
106            Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
107                .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
108                .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
109        }
110        if workspace.isIndexing {
111            ToolbarItem { ProgressView().controlSize(.small) }
112        }
113        if let running = clock.running {
114            ToolbarItem {
115                Menu {
116                    Button("Clock Out") { perform("app.clock.out") }
117                    Button("Cancel Clock") { perform("app.clock.cancel") }
118                    Button("Go to Clocked Entry") { perform("app.clock.goto") }
119                } label: {
120                    TimelineView(.periodic(from: .now, by: 30)) { context in
121                        Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
122                    }
123                }
124                .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
125            }
126        }
127        if session.conflict != nil {
128            ToolbarItem {
129                Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
130                    .help("The file changed on disk, and the changes conflict with yours")
131            }
132        }
133    }
134
135    private var main: some View {
136        NavigationSplitView {
137            Sidebar(workspace: workspace, session: session, selection: $selectedFile) { commands.showingFolderPicker = true }
138                .navigationSplitViewColumnWidth(min: 200, ideal: 260)
139        } detail: {
140            HStack(spacing: 0) {
141                if outlineShown {
142                    Group {
143                        if query.isEmpty {
144                            OutlineColumn(session: session)
145                        } else {
146                            SearchResults(results: workspace.search(query, overlay: workspace.overlay(path: session.path, document: session.document))) { location in
147                                guard location.path == session.path || UnsavedChanges.resolve(session) else { return }
148                                selectedFile = location.path
149                                session.show(location)
150                            }
151                        }
152                    }
153                    .frame(width: CGFloat(outlineWidth))
154                    PaneDivider(width: $outlineWidth, range: 160...400)
155                }
156                detail
157                    .frame(maxWidth: .infinity)
158            }
159        }
160        .navigationTitle((previewPath ?? session.path).map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
161        .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
162        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
163        .searchFocused($searchFocused)
164        .toolbar { toolbarItems }
165        .onChange(of: session.path) { plainOutlineShown = false }
166        .onChange(of: selectedFile) { old, path in
167            guard let path else { return }
168            if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
169                previewPath = path
170                return
171            }
172            previewPath = nil
173            guard path != session.path else { return }
174            if UnsavedChanges.resolve(session) {
175                session.open(path)
176            } else {
177                selectedFile = old
178            }
179        }
180        .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
181        .onChange(of: options, initial: true) { _, options in session.options = options }
182        .onChange(of: preset, initial: true) { loadKeymap() }
183        .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
184        .sheet(isPresented: $commands.showingPalette) {
185            PaletteView(commands: commands) { id in
186                commands.showingPalette = false
187                // After the sheet closes, so app commands can present their own.
188                DispatchQueue.main.async { perform(id) }
189            }
190        }
191        .onChange(of: session.conflict) { _, conflict in
192            if conflict != nil { commands.showingConflict = true }
193        }
194        .alert("Conflicting changes", isPresented: $commands.showingConflict) {
195            Button("Keep Mine") { session.keepMine() }
196            Button("Use Disk Version") { session.useDiskVersion() }
197            Button("Decide Later", role: .cancel) {}
198        } message: {
199            Text((session.conflict ?? "") + " The version you don't keep is saved in the recovery folder.")
200        }
201        .onChange(of: workspace.changedFile?.version) {
202            if let path = workspace.changedFile?.path { session.fileChanged(path) }
203        }
204    }
205
206    var body: some View {
207        main
208        .onChange(of: clock.running, initial: true) { _, running in
209            if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
210            statusItem?.update(running)
211        }
212        .onChange(of: globalCapture, initial: true) { _, enabled in
213            hotKey?.unregister()
214            hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
215        }
216        .onChange(of: commands.runRequest?.serial) {
217            if let id = commands.runRequest?.id { perform(id) }
218        }
219        .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
220            if let first = problems.first {
221                commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
222            }
223        }
224        .onChange(of: ConfigSync.shared.changedFile?.serial) {
225            if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
226        }
227        .onChange(of: commands.jumpRequest?.id) {
228            guard let request = commands.jumpRequest else { return }
229            if request.path != session.path {
230                guard UnsavedChanges.resolve(session) else { return }
231                session.open(request.path)
232                selectedFile = request.path
233            }
234            session.reveal(request.offset)
235        }
236        .onChange(of: commands.focusSearch) { _, focus in
237            if focus {
238                searchFocused = true
239                commands.focusSearch = false
240            }
241        }
242        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
243            guard case .success(let url) = result else { return }
244            Task {
245                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
246            }
247        }
248        .sheet(isPresented: $commands.showingQuickOpen) {
249            QuickOpenView(workspace: workspace) { entry in
250                selectedFile = entry.path
251                commands.showingQuickOpen = false
252            }
253        }
254        .alert("Orgstar", isPresented: errorShown) {
255            Button("OK") {
256                workspace.lastError = nil
257                session.lastError = nil
258            }
259        } message: {
260            Text(workspace.lastError ?? session.lastError ?? "")
261        }
262        .task(id: ReminderKey(
263            enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
264            changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
265        )) {
266            await updateReminders()
267        }
268        .task {
269            while !Task.isCancelled {
270                try? await Task.sleep(for: .seconds(3600))
271                hour += 1
272            }
273        }
274        .task {
275            DevelopmentHooks.scheduleSnapshot()
276            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
277            if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
278            if let command = DevelopmentHooks.commandToRun { perform(command) }
279            if let id = DevelopmentHooks.windowToOpen {
280                if id == "settings" { openSettings() } else { openWindow(id: id) }
281            }
282            await workspace.refresh()
283            workspace.startWatching()
284        }
285    }
286
287    /// Writes the export beside the file, as Emacs's export dispatcher does.
288    private func export(_ format: String) {
289        guard let path = session.path, let text = session.document?.text else {
290            commands.show("No file is open")
291            return
292        }
293        let url = URL(fileURLWithPath: path)
294        let base = url.deletingPathExtension()
295        let defaults = Preferences.orgSettings
296        switch format {
297        case "html", "html-open", "markdown":
298            let target = base.appendingPathExtension(format == "markdown" ? "md" : "html")
299            let content = format == "markdown"
300                ? MarkdownExport.document(text, settings: defaults)
301                : HTMLExport.page(text, fallbackTitle: base.lastPathComponent, settings: defaults)
302            do {
303                try content.write(to: target, atomically: true, encoding: .utf8)
304                commands.show("Exported to \(target.lastPathComponent)")
305                if format == "html-open" { NSWorkspace.shared.open(target) }
306            } catch {
307                commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
308            }
309        default:
310            let functions = ["pdf": "org-latex-export-to-pdf", "odt": "org-odt-export-to-odt", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
311            guard let function = functions[format] else { return }
312            commands.show("Exporting with Emacs…")
313            Task {
314                do {
315                    let written = try await EmacsRunner.export(text: text, path: path, function: function)
316                    commands.show("Exported to \((written as NSString).lastPathComponent)")
317                } catch {
318                    commands.show("\(error)")
319                }
320            }
321        }
322    }
323
324    /// Work a command hands to the platform: tables recalculated in Emacs.
325    private func runExternal(_ request: ExternalRequest) {
326        switch request {
327        case .emacsTable(let table, let point, let form, let reason, let lisp):
328            let run = {
329                commands.show("Recalculating in Emacs (\(reason))…")
330                Task { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
331            }
332            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
333            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
334            if trust.isTrusted(path: path, content: content) { return run() }
335            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
336                switch answer {
337                case "always":
338                    trust.trust(path: path, content: content)
339                    run()
340                case "yes": run()
341                default: commands.show("Not recalculated")
342                }
343            }
344        case .babel(let job):
345            let run = {
346                commands.show("Running \(job.language) block…")
347                Task { commands.show(await session.runBabel(job)) }
348            }
349            guard let path = session.path else { return }
350            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
351            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
352            commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
353                switch answer {
354                case "always":
355                    trust.trust(path: path, content: job.blockText)
356                    run()
357                case "yes": run()
358                default: commands.show("Not run")
359                }
360            }
361        }
362    }
363
364    private struct ReminderKey: Hashable {
365        var enabled: Bool
366        var lead: Int
367        var subfolders: Bool
368        var files: Int
369        var changed: Int?
370        var edits: Int
371        var hour: Int
372    }
373
374    /// Sets the notifications for the next week's timed entries, once edits pause.
375    private func updateReminders() async {
376        guard let scheduler else { return }
377        guard remindersEnabled else {
378            await scheduler.clear()
379            return
380        }
381        try? await Task.sleep(for: .seconds(2))
382        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
383        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
384        reminderAgenda = agenda
385        agenda.includeSubfolders = agendaSubfolders
386        let open = session.path.flatMap { path in session.document.map { (path, $0.text) } }
387        let reminders = await agenda.reminders(open: open, lead: reminderLead)
388        guard !Task.isCancelled else { return }
389        await scheduler.reconcile(reminders)
390    }
391
392    private func loadKeymap() {
393        let loaded = KeymapLoader.load(preset)
394        keymap = loaded.keymap
395        commands.keymap = loaded.keymap
396        commands.modal = preset.isModal
397        if let first = loaded.problems.first {
398            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
399            commands.show("keymap.toml: \(first)\(more)")
400        }
401    }
402
403    /// Runs a command from a key, the palette or the Org menu.
404    private func perform(_ id: String) {
405        let orgOnly = ["app.refile", "app.archive", "app.clock.in"].contains(id) || id.hasPrefix("app.export.")
406        if orgOnly, !session.isOrg {
407            commands.show("Not an org file")
408            return
409        }
410        switch id {
411        case "app.save":
412            if !session.save(), session.conflict != nil { commands.showingConflict = true }
413        case "app.quit": NSApp.terminate(nil)
414        case "app.toggle-outline": toggleOutline()
415        case "app.toggle-markup": showMarkup.toggle()
416        case "app.toggle-line-numbers": showLineNumbers.toggle()
417        case "app.import-emacs": showingImport = true
418        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
419        case "app.quick-open": commands.showingQuickOpen = true
420        case "app.palette": commands.showingPalette = true
421        case "app.search": commands.focusSearch = true
422        case "app.reload-keymap":
423            loadKeymap()
424            commands.show("Keymap reloaded")
425        case "app.refile":
426            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
427            commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
428                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
429                if let message = session.refile(to: target) { commands.show(message) }
430            }
431        case "app.archive":
432            if let message = session.archive() { commands.show(message) }
433        case "app.agenda":
434            openWindow(id: "agenda")
435        case "app.clock.in":
436            commands.show(clock.clockIn(session))
437        case "app.clock.out":
438            commands.show(clock.clockOut(session))
439        case "app.clock.cancel":
440            commands.show(clock.clockOut(session, cancel: true))
441        case "app.clock.goto":
442            if let location = clock.location(session) { commands.jump(path: location.path, offset: location.offset) } else { commands.show("No active clock") }
443        case "app.clock.report":
444            openWindow(id: "clock-report")
445        case "app.board":
446            openWindow(id: "board")
447        case "app.capture":
448            NSApp.activate()
449            openWindow(id: "capture")
450        case let id where id.hasPrefix("app.export."):
451            export(String(id.dropFirst("app.export.".count)))
452        default:
453            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
454        }
455    }
456
457    private var errorShown: Binding<Bool> {
458        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
459    }
460}
461
462struct Sidebar: View {
463    let workspace: WorkspaceModel
464    let session: DocumentSession
465    @Binding var selection: String?
466    var addFolder: () -> Void = {}
467    /// Folders shown collapsed, by path, one per line.
468    @AppStorage("collapsedFolders") private var collapsedText = ""
469    @State private var removing: String?
470    /// A file operation waiting for a name or a confirmation.
471    @State var pending: FileOperation?
472    @State var name = ""
473    @State var failure: String?
474
475    private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) }
476
477    private func expanded(_ root: String) -> Binding<Bool> {
478        Binding {
479            !collapsed.contains(root)
480        } set: { isExpanded in
481            var set = collapsed
482            if isExpanded { set.remove(root) } else { set.insert(root) }
483            collapsedText = set.sorted().joined(separator: "\n")
484        }
485    }
486
487    var body: some View {
488        List(selection: $selection) {
489            ForEach(workspace.rootPaths, id: \.self) { root in
490                Section(isExpanded: expanded(root)) {
491                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
492                        Label(node.name, systemImage: icon(node))
493                            .foregroundStyle(node.file?.kind == .conflict ? .orange : .primary)
494                            .tag(node.file?.path)
495                            .contextMenu { fileMenu(node) }
496                    }
497                } header: {
498                    Text((root as NSString).lastPathComponent)
499                        .help(root)
500                        .contextMenu { folderMenu(root) }
501                }
502            }
503        }
504        .listStyle(.sidebar)
505        .safeAreaInset(edge: .bottom, spacing: 0) {
506            HStack(spacing: 4) {
507                Button("Add Folder…", systemImage: "plus", action: addFolder)
508                    .help("Add a folder (⇧⌘O)")
509                Menu {
510                    ForEach(workspace.rootPaths, id: \.self) { root in
511                        Button((root as NSString).lastPathComponent) { removing = root }
512                    }
513                } label: {
514                    Label("Remove Folder", systemImage: "minus")
515                }
516                .menuIndicator(.hidden)
517                .fixedSize()
518                .disabled(workspace.rootPaths.isEmpty)
519                .help("Remove a folder from the sidebar")
520                Spacer()
521            }
522            .labelStyle(.iconOnly)
523            .buttonStyle(.borderless)
524            .menuStyle(.borderlessButton)
525            .padding(.horizontal, 10)
526            .padding(.vertical, 6)
527        }
528        .confirmationDialog(
529            "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
530            isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
531        ) {
532            Button("Remove") {
533                if let root = removing { try? workspace.removeRoot(path: root) }
534                removing = nil
535            }
536        } message: {
537            Text("The folder and its files stay on disk.")
538        }
539        .fileOperations(self)
540    }
541
542    @ViewBuilder
543    private func folderMenu(_ root: String) -> some View {
544        Button("New File…") { ask(.create(folder: root)) }
545        Divider()
546        Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
547        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
548        Divider()
549        Button("Remove from Sidebar…") { removing = root }
550    }
551
552    private func icon(_ node: FileTreeNode) -> String {
553        guard let file = node.file else { return "folder" }
554        switch file.kind {
555        case .org: return "doc.text"
556        case .archive: return "archivebox"
557        case .conflict: return "exclamationmark.triangle"
558        case .other:
559            guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
560            if type.conforms(to: .image) { return "photo" }
561            if type.conforms(to: .pdf) { return "doc.richtext" }
562            if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
563            if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
564            if type.conforms(to: .text) { return "doc.plaintext" }
565            return "doc"
566        }
567    }
568}
569
570struct OutlineColumn: View {
571    let session: DocumentSession
572
573    var body: some View {
574        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
575            Button {
576                session.reveal(entry.start)
577            } label: {
578                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
579                    .lineLimit(1)
580                    .padding(.leading, CGFloat(entry.level - 1) * 12)
581            }
582            .buttonStyle(.plain)
583        }
584        .overlay {
585            if session.path != nil, !session.isOrg {
586                ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
587            } else if session.path != nil, session.outline.isEmpty {
588                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
589            }
590        }
591    }
592}
593
594struct SearchResults: View {
595    let results: [HeadingLocation]
596    let open: (HeadingLocation) -> Void
597
598    var body: some View {
599        List(results, id: \.self) { location in
600            Button {
601                open(location)
602            } label: {
603                VStack(alignment: .leading, spacing: 2) {
604                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
605                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
606                }
607            }
608            .buttonStyle(.plain)
609        }
610        .overlay {
611            if results.isEmpty { ContentUnavailableView.search }
612        }
613    }
614}
615
616struct QuickOpenView: View {
617    let workspace: WorkspaceModel
618    let open: (FileEntry) -> Void
619    @State private var query = ""
620    @Environment(\.dismiss) private var dismiss
621
622    var body: some View {
623        let matches = workspace.quickOpen(query)
624        VStack(spacing: 0) {
625            TextField("Open file", text: $query)
626                .textFieldStyle(.plain)
627                .font(.title3)
628                .padding(12)
629                .onSubmit { if let first = matches.first { open(first) } }
630            Divider()
631            List(matches) { entry in
632                Button {
633                    open(entry)
634                } label: {
635                    VStack(alignment: .leading, spacing: 2) {
636                        Text(entry.name)
637                        Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
638                    }
639                }
640                .buttonStyle(.plain)
641            }
642        }
643        .frame(width: 520, height: 360)
644        .onExitCommand { dismiss() }
645    }
646}
647
648/// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's
649/// split view loops on its size constraints in short windows, so this sets a width instead.
650struct PaneDivider: View {
651    @Binding var width: Double
652    let range: ClosedRange<Double>
653    @State private var start: Double?
654
655    var body: some View {
656        Rectangle()
657            .fill(Color(nsColor: .separatorColor))
658            .frame(width: 1)
659            .frame(maxHeight: .infinity)
660            .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in
661                if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() }
662            }
663            .gesture(DragGesture(minimumDistance: 1).onChanged { drag in
664                let base = start ?? width
665                start = base
666                width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound)
667            }.onEnded { _ in start = nil }))
668            .accessibilityHidden(true)
669    }
670}