Sources/Orgstar/ContentView.swift

2cd54205f32212a32ac7cf2a011c7b019f3745c5
orgstar/Sources/Orgstar/ContentView.swift

783 lines · 35589 bytes

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