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