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