Sources/Orgstar/ContentView.swift

24ce0772eaab6c1bbdee07384de234975cf3769b
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

366 lines · 15543 bytes

  1import OrgApp
  2import OrgCore
  3import OrgEditorAppKit
  4import OrgIndex
  5import SwiftUI
  6
  7struct ContentView: View {
  8    let workspace: WorkspaceModel
  9    let session: DocumentSession
 10    @Bindable var commands: AppCommands
 11    let scheduler: ReminderScheduler?
 12    @AppStorage("reminders") private var remindersEnabled = true
 13    @AppStorage("reminderLead") private var reminderLead = 12
 14    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
 15    @State private var reminderAgenda: AgendaModel?
 16    @State private var trust = TrustStore()
 17    @State private var hour = 0
 18    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 19    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 20    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 21    @State private var keymap = KeymapPreset.emacs.keymap
 22    @AppStorage("tagsColumn") private var tagsColumn = -77
 23    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
 24    @AppStorage("splitLine") private var splitLine = false
 25    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 26    @AppStorage("fillColumn") private var fillColumn = 80
 27    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 28    @AppStorage("prettyEntities") private var prettyEntities = true
 29
 30    private var options: EditingOptions {
 31        Preferences.options(
 32            tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
 33            fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities
 34        )
 35    }
 36    @State private var selectedFile: String?
 37    @State private var query = ""
 38    @FocusState private var searchFocused: Bool
 39    @Environment(\.openWindow) private var openWindow
 40
 41    var body: some View {
 42        NavigationSplitView {
 43            Sidebar(workspace: workspace, selection: $selectedFile)
 44                .navigationSplitViewColumnWidth(min: 200, ideal: 260)
 45        } content: {
 46            Group {
 47                if query.isEmpty {
 48                    OutlineColumn(session: session)
 49                } else {
 50                    SearchResults(results: workspace.search(query, overlay: workspace.overlay(path: session.path, document: session.document))) { location in
 51                        guard location.path == session.path || UnsavedChanges.resolve(session) else { return }
 52                        selectedFile = location.path
 53                        session.show(location)
 54                    }
 55                }
 56            }
 57            .navigationSplitViewColumnWidth(min: 160, ideal: 220, max: 360)
 58        } detail: {
 59            if session.path != nil {
 60                EditorView(session: session, commands: commands, keymap: keymap, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, onAppCommand: perform, onExternal: runExternal)
 61                    .safeAreaInset(edge: .bottom, spacing: 0) { EchoArea(commands: commands) }
 62            } else {
 63                ContentUnavailableView(
 64                    workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
 65                    systemImage: "doc.text",
 66                    description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
 67                )
 68            }
 69        }
 70        .navigationTitle(session.path.map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
 71        .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
 72        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
 73        .searchFocused($searchFocused)
 74        .toolbar {
 75            if workspace.isIndexing { ProgressView().controlSize(.small) }
 76            if session.conflict != nil {
 77                Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
 78                    .help("The file changed on disk, and the changes conflict with yours")
 79            }
 80        }
 81        .onChange(of: selectedFile) { old, path in
 82            guard let path, path != session.path else { return }
 83            if UnsavedChanges.resolve(session) {
 84                session.open(path)
 85            } else {
 86                selectedFile = old
 87            }
 88        }
 89        .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
 90        .onChange(of: options, initial: true) { _, options in session.options = options }
 91        .onChange(of: preset, initial: true) { loadKeymap() }
 92        .sheet(isPresented: $commands.showingPalette) {
 93            PaletteView(keymap: keymap) { id in
 94                commands.showingPalette = false
 95                // After the sheet closes, so app commands can present their own.
 96                DispatchQueue.main.async { perform(id) }
 97            }
 98        }
 99        .onChange(of: session.conflict) { _, conflict in
100            if conflict != nil { commands.showingConflict = true }
101        }
102        .alert("Conflicting changes", isPresented: $commands.showingConflict) {
103            Button("Keep Mine") { session.keepMine() }
104            Button("Use Disk Version") { session.useDiskVersion() }
105            Button("Decide Later", role: .cancel) {}
106        } message: {
107            Text((session.conflict ?? "") + " The version you don't keep is saved in the recovery folder.")
108        }
109        .onChange(of: workspace.changedFile?.version) {
110            if let path = workspace.changedFile?.path { session.fileChanged(path) }
111        }
112        .onChange(of: commands.jumpRequest?.id) {
113            guard let request = commands.jumpRequest else { return }
114            if request.path != session.path {
115                guard UnsavedChanges.resolve(session) else { return }
116                session.open(request.path)
117                selectedFile = request.path
118            }
119            session.reveal(request.offset)
120        }
121        .onChange(of: commands.focusSearch) { _, focus in
122            if focus {
123                searchFocused = true
124                commands.focusSearch = false
125            }
126        }
127        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
128            guard case .success(let url) = result else { return }
129            Task {
130                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
131            }
132        }
133        .sheet(isPresented: $commands.showingQuickOpen) {
134            QuickOpenView(workspace: workspace) { entry in
135                selectedFile = entry.path
136                commands.showingQuickOpen = false
137            }
138        }
139        .alert("Orgstar", isPresented: errorShown) {
140            Button("OK") {
141                workspace.lastError = nil
142                session.lastError = nil
143            }
144        } message: {
145            Text(workspace.lastError ?? session.lastError ?? "")
146        }
147        .task(id: ReminderKey(
148            enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
149            changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
150        )) {
151            await updateReminders()
152        }
153        .task {
154            while !Task.isCancelled {
155                try? await Task.sleep(for: .seconds(3600))
156                hour += 1
157            }
158        }
159        .task {
160            DevelopmentHooks.scheduleSnapshot()
161            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
162            if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
163            if let id = DevelopmentHooks.windowToOpen { openWindow(id: id) }
164            await workspace.refresh()
165            workspace.startWatching()
166        }
167    }
168
169    /// Work a command hands to the platform: tables recalculated in Emacs.
170    private func runExternal(_ request: ExternalRequest) {
171        switch request {
172        case .emacsTable(let table, let point, let form, let reason, let lisp):
173            let run = {
174                commands.show("Recalculating in Emacs (\(reason))…")
175                Task { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
176            }
177            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
178            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
179            if trust.isTrusted(path: path, content: content) { return run() }
180            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
181                switch answer {
182                case "always":
183                    trust.trust(path: path, content: content)
184                    run()
185                case "yes": run()
186                default: commands.show("Not recalculated")
187                }
188            }
189        }
190    }
191
192    private struct ReminderKey: Hashable {
193        var enabled: Bool
194        var lead: Int
195        var subfolders: Bool
196        var files: Int
197        var changed: Int?
198        var edits: Int
199        var hour: Int
200    }
201
202    /// Sets the notifications for the next week's timed entries, once edits pause.
203    private func updateReminders() async {
204        guard let scheduler else { return }
205        guard remindersEnabled else {
206            await scheduler.clear()
207            return
208        }
209        try? await Task.sleep(for: .seconds(2))
210        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
211        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
212        reminderAgenda = agenda
213        agenda.includeSubfolders = agendaSubfolders
214        let open = session.path.flatMap { path in session.document.map { (path, $0.text) } }
215        let reminders = await agenda.reminders(open: open, lead: reminderLead)
216        guard !Task.isCancelled else { return }
217        await scheduler.reconcile(reminders)
218    }
219
220    private func loadKeymap() {
221        let loaded = KeymapLoader.load(preset)
222        keymap = loaded.keymap
223        if let first = loaded.problems.first {
224            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
225            commands.show("keymap.toml: \(first)\(more)")
226        }
227    }
228
229    /// Runs a command from a key, the palette or the Org menu.
230    private func perform(_ id: String) {
231        switch id {
232        case "app.save":
233            if !session.save(), session.conflict != nil { commands.showingConflict = true }
234        case "app.quick-open": commands.showingQuickOpen = true
235        case "app.palette": commands.showingPalette = true
236        case "app.search": commands.focusSearch = true
237        case "app.reload-keymap":
238            loadKeymap()
239            commands.show("Keymap reloaded")
240        case "app.refile":
241            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
242            commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
243                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
244                if let message = session.refile(to: target) { commands.show(message) }
245            }
246        case "app.archive":
247            if let message = session.archive() { commands.show(message) }
248        case "app.agenda":
249            openWindow(id: "agenda")
250        default:
251            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
252        }
253    }
254
255    private var errorShown: Binding<Bool> {
256        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
257    }
258}
259
260struct Sidebar: View {
261    let workspace: WorkspaceModel
262    @Binding var selection: String?
263
264    var body: some View {
265        List(selection: $selection) {
266            ForEach(workspace.rootPaths, id: \.self) { root in
267                Section((root as NSString).lastPathComponent) {
268                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
269                        Label(node.name, systemImage: icon(node))
270                            .foregroundStyle(node.file?.kind == .conflict ? .orange : .primary)
271                            .tag(node.file?.path)
272                    }
273                }
274                .contextMenu {
275                    Button("Remove Folder") { try? workspace.removeRoot(path: root) }
276                }
277            }
278        }
279        .listStyle(.sidebar)
280    }
281
282    private func icon(_ node: FileTreeNode) -> String {
283        guard let file = node.file else { return "folder" }
284        switch file.kind {
285        case .org: return "doc.text"
286        case .archive: return "archivebox"
287        case .conflict: return "exclamationmark.triangle"
288        }
289    }
290}
291
292struct OutlineColumn: View {
293    let session: DocumentSession
294
295    var body: some View {
296        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
297            Button {
298                session.reveal(entry.start)
299            } label: {
300                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
301                    .lineLimit(1)
302                    .padding(.leading, CGFloat(entry.level - 1) * 12)
303            }
304            .buttonStyle(.plain)
305        }
306        .overlay {
307            if session.path != nil, session.outline.isEmpty {
308                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
309            }
310        }
311    }
312}
313
314struct SearchResults: View {
315    let results: [HeadingLocation]
316    let open: (HeadingLocation) -> Void
317
318    var body: some View {
319        List(results, id: \.self) { location in
320            Button {
321                open(location)
322            } label: {
323                VStack(alignment: .leading, spacing: 2) {
324                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
325                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
326                }
327            }
328            .buttonStyle(.plain)
329        }
330        .overlay {
331            if results.isEmpty { ContentUnavailableView.search }
332        }
333    }
334}
335
336struct QuickOpenView: View {
337    let workspace: WorkspaceModel
338    let open: (FileEntry) -> Void
339    @State private var query = ""
340    @Environment(\.dismiss) private var dismiss
341
342    var body: some View {
343        let matches = workspace.quickOpen(query)
344        VStack(spacing: 0) {
345            TextField("Open file", text: $query)
346                .textFieldStyle(.plain)
347                .font(.title3)
348                .padding(12)
349                .onSubmit { if let first = matches.first { open(first) } }
350            Divider()
351            List(matches) { entry in
352                Button {
353                    open(entry)
354                } label: {
355                    VStack(alignment: .leading, spacing: 2) {
356                        Text(entry.name)
357                        Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
358                    }
359                }
360                .buttonStyle(.plain)
361            }
362        }
363        .frame(width: 520, height: 360)
364        .onExitCommand { dismiss() }
365    }
366}