Sources/Orgstar/ContentView.swift

8747c1880dce12825eeb095776dcba284ca4f646
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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