Sources/Orgstar/ContentView.swift

3dd5b060e7ddb3d4d7f0fc2e06a7b09a3eb5a546
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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