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