Sources/Orgstar/ContentView.swift

a6139aad417b2a36bcbaca055d07319ffb0226da
orgstar/Sources/Orgstar/ContentView.swift

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