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