Sources/Orgstar/ContentView.swift

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

629 lines · 27982 bytes

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