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