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