Sources/Orgstar/ContentView.swift
778 lines · 35237 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… (⌘. to cancel)")
362 session.startBabel(job) { commands.show($0) }
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.babel.cancel":
465 if session.isRunningBabel { session.cancelBabel() } else { commands.show("No block is running") }
466 case "app.toggle-outline": toggleOutline()
467 case "app.toggle-markup": showMarkup.toggle()
468 case "app.toggle-line-numbers": showLineNumbers.toggle()
469 case "app.import-emacs": showingImport = true
470 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
471 case "app.quick-open": commands.showingQuickOpen = true
472 case "app.palette": commands.showingPalette = true
473 case "app.search": commands.focusSearch = true
474 case "app.reload-keymap":
475 loadKeymap()
476 commands.show("Keymap reloaded")
477 case "app.refile":
478 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
479 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
480 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
481 if let message = session.refile(to: target) { commands.show(message) }
482 }
483 case "app.archive":
484 if let message = session.archive() { commands.show(message) }
485 case "app.agenda":
486 openWindow(id: "agenda")
487 case "app.clock.in":
488 commands.show(clock.clockIn(session))
489 case "app.clock.out":
490 commands.show(clock.clockOut(session))
491 case "app.clock.cancel":
492 commands.show(clock.clockOut(session, cancel: true))
493 case "app.clock.goto":
494 if let location = clock.location(session) { commands.jump(path: location.path, offset: location.offset) } else { commands.show("No active clock") }
495 case "app.clock.report":
496 openWindow(id: "clock-report")
497 case "app.board":
498 openWindow(id: "board")
499 case "app.capture":
500 NSApp.activate()
501 openWindow(id: "capture")
502 case let id where id.hasPrefix("app.export."):
503 export(String(id.dropFirst("app.export.".count)))
504 default:
505 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
506 }
507 }
508
509 private var errorShown: Binding<Bool> {
510 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
511 }
512}
513
514struct Sidebar: View {
515 let workspace: WorkspaceModel
516 let session: DocumentSession
517 @Binding var selection: String?
518 var addFolder: () -> Void = {}
519 /// Folders shown collapsed, by path, one per line.
520 @AppStorage("collapsedFolders") private var collapsedText = ""
521 @State private var removing: String?
522 /// A file operation waiting for a name or a confirmation.
523 @Environment(\.orgTheme) private var theme
524 @State var pending: FileOperation?
525 @State var name = ""
526 @State var failure: String?
527
528 private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) }
529
530 private func expanded(_ root: String) -> Binding<Bool> {
531 Binding {
532 !collapsed.contains(root)
533 } set: { isExpanded in
534 var set = collapsed
535 if isExpanded { set.remove(root) } else { set.insert(root) }
536 collapsedText = set.sorted().joined(separator: "\n")
537 }
538 }
539
540 var body: some View {
541 List(selection: $selection) {
542 ForEach(workspace.rootPaths, id: \.self) { root in
543 Section(isExpanded: expanded(root)) {
544 OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
545 Label(node.name, systemImage: icon(node))
546 .foregroundStyle(node.file?.kind == .conflict ? .orange : theme.color("sidebar-foreground") ?? .primary)
547 .tag(node.file?.path)
548 .contextMenu { fileMenu(node) }
549 }
550 } header: {
551 Text((root as NSString).lastPathComponent)
552 .foregroundStyle(theme.color("sidebar-header") ?? .secondary)
553 .help(root)
554 .contextMenu { folderMenu(root) }
555 }
556 }
557 }
558 .listStyle(.sidebar)
559 .themedListBackground(theme.color("sidebar-background"))
560 .safeAreaInset(edge: .bottom, spacing: 0) {
561 HStack(spacing: 4) {
562 Button("Add Folder…", systemImage: "plus", action: addFolder)
563 .help("Add a folder (⇧⌘O)")
564 Menu {
565 ForEach(workspace.rootPaths, id: \.self) { root in
566 Button((root as NSString).lastPathComponent) { removing = root }
567 }
568 } label: {
569 Label("Remove Folder", systemImage: "minus")
570 }
571 .menuIndicator(.hidden)
572 .fixedSize()
573 .disabled(workspace.rootPaths.isEmpty)
574 .help("Remove a folder from the sidebar")
575 Spacer()
576 }
577 .labelStyle(.iconOnly)
578 .buttonStyle(.borderless)
579 .menuStyle(.borderlessButton)
580 .padding(.horizontal, 10)
581 .padding(.vertical, 6)
582 }
583 .confirmationDialog(
584 "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
585 isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
586 ) {
587 Button("Remove") {
588 if let root = removing { try? workspace.removeRoot(path: root) }
589 removing = nil
590 }
591 } message: {
592 Text("The folder and its files stay on disk.")
593 }
594 .fileOperations(self)
595 }
596
597 @ViewBuilder
598 private func folderMenu(_ root: String) -> some View {
599 Button("New File…") { ask(.create(folder: root)) }
600 Divider()
601 Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
602 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
603 Divider()
604 Button("Remove from Sidebar…") { removing = root }
605 }
606
607 private func icon(_ node: FileTreeNode) -> String {
608 guard let file = node.file else { return "folder" }
609 switch file.kind {
610 case .org: return "doc.text"
611 case .archive: return "archivebox"
612 case .conflict: return "exclamationmark.triangle"
613 case .other:
614 guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
615 if type.conforms(to: .image) { return "photo" }
616 if type.conforms(to: .pdf) { return "doc.richtext" }
617 if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
618 if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
619 if type.conforms(to: .text) { return "doc.plaintext" }
620 return "doc"
621 }
622 }
623}
624
625struct OutlineColumn: View {
626 let session: DocumentSession
627 @Environment(\.orgTheme) private var theme
628
629 var body: some View {
630 List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
631 Button {
632 session.reveal(entry.start)
633 } label: {
634 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
635 .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
636 .lineLimit(1)
637 .padding(.leading, CGFloat(entry.level - 1) * 12)
638 }
639 .buttonStyle(.plain)
640 }
641 .themedListBackground(theme.color("sidebar-background"))
642 .overlay {
643 if session.path != nil, !session.isOrg {
644 ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
645 } else if session.path != nil, session.outline.isEmpty {
646 ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
647 }
648 }
649 }
650}
651
652struct SearchResults: View {
653 let results: [HeadingLocation]
654 let open: (HeadingLocation) -> Void
655
656 var body: some View {
657 List(results, id: \.self) { location in
658 Button {
659 open(location)
660 } label: {
661 VStack(alignment: .leading, spacing: 2) {
662 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
663 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
664 }
665 }
666 .buttonStyle(.plain)
667 }
668 .overlay {
669 if results.isEmpty { ContentUnavailableView.search }
670 }
671 }
672}
673
674struct QuickOpenView: View {
675 let workspace: WorkspaceModel
676 let open: (FileEntry) -> Void
677 @State private var query = ""
678 @Environment(\.dismiss) private var dismiss
679
680 var body: some View {
681 let matches = workspace.quickOpen(query)
682 VStack(spacing: 0) {
683 TextField("Open file", text: $query)
684 .textFieldStyle(.plain)
685 .font(.title3)
686 .padding(12)
687 .onSubmit { if let first = matches.first { open(first) } }
688 Divider()
689 List(matches) { entry in
690 Button {
691 open(entry)
692 } label: {
693 VStack(alignment: .leading, spacing: 2) {
694 Text(entry.name)
695 Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
696 }
697 }
698 .buttonStyle(.plain)
699 }
700 }
701 .frame(width: 520, height: 360)
702 .onExitCommand { dismiss() }
703 }
704}
705
706/// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's
707/// split view loops on its size constraints in short windows, so this sets a width instead.
708struct PaneDivider: View {
709 @Binding var width: Double
710 let range: ClosedRange<Double>
711 @State private var start: Double?
712
713 var body: some View {
714 Rectangle()
715 .fill(Color(nsColor: .separatorColor))
716 .frame(width: 1)
717 .frame(maxHeight: .infinity)
718 .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in
719 if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() }
720 }
721 .gesture(DragGesture(minimumDistance: 1).onChanged { drag in
722 let base = start ?? width
723 start = base
724 width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound)
725 }.onEnded { _ in start = nil }))
726 .accessibilityHidden(true)
727 }
728}
729
730/// A tab for each open buffer: click to show it, × to close it, a dot for unsaved edits.
731struct BufferTabs: View {
732 let session: DocumentSession
733 @Environment(\.orgTheme) private var theme
734
735 var body: some View {
736 ScrollView(.horizontal, showsIndicators: false) {
737 HStack(spacing: 0) {
738 ForEach(session.openPaths, id: \.self) { path in
739 tab(path)
740 }
741 }
742 }
743 .frame(height: 28)
744 .background { Rectangle().fill(theme.color("modeline-background").map(AnyShapeStyle.init) ?? AnyShapeStyle(.bar)) }
745 .overlay(alignment: .bottom) { Divider() }
746 }
747
748 private func tab(_ path: String) -> some View {
749 let current = path == session.path
750 return HStack(spacing: 6) {
751 Text((path as NSString).lastPathComponent)
752 .lineLimit(1)
753 .foregroundStyle(current ? .primary : .secondary)
754 Button {
755 if path == session.path {
756 if UnsavedChanges.resolve(session) { session.kill(path) }
757 } else if UnsavedChanges.resolve(session, paths: [path]) {
758 session.kill(path)
759 }
760 } label: {
761 Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark")
762 .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold))
763 .frame(width: 12, height: 12)
764 }
765 .buttonStyle(.borderless)
766 .help("Close")
767 }
768 .font(.callout)
769 .padding(.horizontal, 12)
770 .frame(maxHeight: .infinity)
771 // A shape, not a color: a color background runs up under the toolbar.
772 .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) }
773 .overlay(alignment: .trailing) { Divider() }
774 .contentShape(Rectangle())
775 .onTapGesture { session.open(path) }
776 .help(path)
777 }
778}