Sources/Orgstar/ContentView.swift

2e692ba274ccc7e69b6b3cfc00edeafbbeef638a
orgstar/Sources/Orgstar/ContentView.swift

806 lines · 37401 bytes

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form