Sources/Orgstar/ContentView.swift
676 lines · 30173 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 @Environment(\.orgTheme) private var theme
472 @State var pending: FileOperation?
473 @State var name = ""
474 @State var failure: String?
475
476 private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) }
477
478 private func expanded(_ root: String) -> Binding<Bool> {
479 Binding {
480 !collapsed.contains(root)
481 } set: { isExpanded in
482 var set = collapsed
483 if isExpanded { set.remove(root) } else { set.insert(root) }
484 collapsedText = set.sorted().joined(separator: "\n")
485 }
486 }
487
488 var body: some View {
489 List(selection: $selection) {
490 ForEach(workspace.rootPaths, id: \.self) { root in
491 Section(isExpanded: expanded(root)) {
492 OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
493 Label(node.name, systemImage: icon(node))
494 .foregroundStyle(node.file?.kind == .conflict ? .orange : theme.color("sidebar-foreground") ?? .primary)
495 .tag(node.file?.path)
496 .contextMenu { fileMenu(node) }
497 }
498 } header: {
499 Text((root as NSString).lastPathComponent)
500 .foregroundStyle(theme.color("sidebar-header") ?? .secondary)
501 .help(root)
502 .contextMenu { folderMenu(root) }
503 }
504 }
505 }
506 .listStyle(.sidebar)
507 .themedListBackground(theme.color("sidebar-background"))
508 .safeAreaInset(edge: .bottom, spacing: 0) {
509 HStack(spacing: 4) {
510 Button("Add Folder…", systemImage: "plus", action: addFolder)
511 .help("Add a folder (⇧⌘O)")
512 Menu {
513 ForEach(workspace.rootPaths, id: \.self) { root in
514 Button((root as NSString).lastPathComponent) { removing = root }
515 }
516 } label: {
517 Label("Remove Folder", systemImage: "minus")
518 }
519 .menuIndicator(.hidden)
520 .fixedSize()
521 .disabled(workspace.rootPaths.isEmpty)
522 .help("Remove a folder from the sidebar")
523 Spacer()
524 }
525 .labelStyle(.iconOnly)
526 .buttonStyle(.borderless)
527 .menuStyle(.borderlessButton)
528 .padding(.horizontal, 10)
529 .padding(.vertical, 6)
530 }
531 .confirmationDialog(
532 "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
533 isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
534 ) {
535 Button("Remove") {
536 if let root = removing { try? workspace.removeRoot(path: root) }
537 removing = nil
538 }
539 } message: {
540 Text("The folder and its files stay on disk.")
541 }
542 .fileOperations(self)
543 }
544
545 @ViewBuilder
546 private func folderMenu(_ root: String) -> some View {
547 Button("New File…") { ask(.create(folder: root)) }
548 Divider()
549 Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
550 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
551 Divider()
552 Button("Remove from Sidebar…") { removing = root }
553 }
554
555 private func icon(_ node: FileTreeNode) -> String {
556 guard let file = node.file else { return "folder" }
557 switch file.kind {
558 case .org: return "doc.text"
559 case .archive: return "archivebox"
560 case .conflict: return "exclamationmark.triangle"
561 case .other:
562 guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
563 if type.conforms(to: .image) { return "photo" }
564 if type.conforms(to: .pdf) { return "doc.richtext" }
565 if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
566 if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
567 if type.conforms(to: .text) { return "doc.plaintext" }
568 return "doc"
569 }
570 }
571}
572
573struct OutlineColumn: View {
574 let session: DocumentSession
575 @Environment(\.orgTheme) private var theme
576
577 var body: some View {
578 List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
579 Button {
580 session.reveal(entry.start)
581 } label: {
582 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
583 .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
584 .lineLimit(1)
585 .padding(.leading, CGFloat(entry.level - 1) * 12)
586 }
587 .buttonStyle(.plain)
588 }
589 .themedListBackground(theme.color("sidebar-background"))
590 .overlay {
591 if session.path != nil, !session.isOrg {
592 ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
593 } else if session.path != nil, session.outline.isEmpty {
594 ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
595 }
596 }
597 }
598}
599
600struct SearchResults: View {
601 let results: [HeadingLocation]
602 let open: (HeadingLocation) -> Void
603
604 var body: some View {
605 List(results, id: \.self) { location in
606 Button {
607 open(location)
608 } label: {
609 VStack(alignment: .leading, spacing: 2) {
610 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
611 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
612 }
613 }
614 .buttonStyle(.plain)
615 }
616 .overlay {
617 if results.isEmpty { ContentUnavailableView.search }
618 }
619 }
620}
621
622struct QuickOpenView: View {
623 let workspace: WorkspaceModel
624 let open: (FileEntry) -> Void
625 @State private var query = ""
626 @Environment(\.dismiss) private var dismiss
627
628 var body: some View {
629 let matches = workspace.quickOpen(query)
630 VStack(spacing: 0) {
631 TextField("Open file", text: $query)
632 .textFieldStyle(.plain)
633 .font(.title3)
634 .padding(12)
635 .onSubmit { if let first = matches.first { open(first) } }
636 Divider()
637 List(matches) { entry in
638 Button {
639 open(entry)
640 } label: {
641 VStack(alignment: .leading, spacing: 2) {
642 Text(entry.name)
643 Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
644 }
645 }
646 .buttonStyle(.plain)
647 }
648 }
649 .frame(width: 520, height: 360)
650 .onExitCommand { dismiss() }
651 }
652}
653
654/// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's
655/// split view loops on its size constraints in short windows, so this sets a width instead.
656struct PaneDivider: View {
657 @Binding var width: Double
658 let range: ClosedRange<Double>
659 @State private var start: Double?
660
661 var body: some View {
662 Rectangle()
663 .fill(Color(nsColor: .separatorColor))
664 .frame(width: 1)
665 .frame(maxHeight: .infinity)
666 .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in
667 if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() }
668 }
669 .gesture(DragGesture(minimumDistance: 1).onChanged { drag in
670 let base = start ?? width
671 start = base
672 width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound)
673 }.onEnded { _ in start = nil }))
674 .accessibilityHidden(true)
675 }
676}