Sources/Orgstar/ContentView.swift

0cfdac07f7253b4bc92725e377a834511f786697
orgstar/Sources/Orgstar/ContentView.swift
cmc Themes0cfdac07f7 1 month ago

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form