Sources/Orgstar/ContentView.swift

2068474b3a12dba3acf176f92115566e0932bda9
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

282 lines · 11657 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    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 12    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 13    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 14    @State private var keymap = KeymapPreset.emacs.keymap
 15    @AppStorage("tagsColumn") private var tagsColumn = -77
 16    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
 17    @AppStorage("splitLine") private var splitLine = false
 18    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 19    @AppStorage("fillColumn") private var fillColumn = 80
 20    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 21    @AppStorage("prettyEntities") private var prettyEntities = true
 22
 23    private var options: EditingOptions {
 24        Preferences.options(
 25            tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
 26            fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities
 27        )
 28    }
 29    @State private var selectedFile: String?
 30    @State private var query = ""
 31    @FocusState private var searchFocused: Bool
 32
 33    var body: some View {
 34        NavigationSplitView {
 35            Sidebar(workspace: workspace, selection: $selectedFile)
 36                .navigationSplitViewColumnWidth(min: 200, ideal: 260)
 37        } content: {
 38            Group {
 39                if query.isEmpty {
 40                    OutlineColumn(session: session)
 41                } else {
 42                    SearchResults(results: workspace.search(query, overlay: workspace.overlay(path: session.path, document: session.document))) { location in
 43                        guard location.path == session.path || UnsavedChanges.resolve(session) else { return }
 44                        selectedFile = location.path
 45                        session.show(location)
 46                    }
 47                }
 48            }
 49            .navigationSplitViewColumnWidth(min: 160, ideal: 220, max: 360)
 50        } detail: {
 51            if session.path != nil {
 52                EditorView(session: session, commands: commands, keymap: keymap, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, onAppCommand: perform)
 53                    .safeAreaInset(edge: .bottom, spacing: 0) { EchoArea(commands: commands) }
 54            } else {
 55                ContentUnavailableView(
 56                    workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
 57                    systemImage: "doc.text",
 58                    description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
 59                )
 60            }
 61        }
 62        .navigationTitle(session.path.map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
 63        .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
 64        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
 65        .searchFocused($searchFocused)
 66        .toolbar {
 67            if workspace.isIndexing { ProgressView().controlSize(.small) }
 68            if session.conflict != nil {
 69                Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
 70                    .help("The file changed on disk, and the changes conflict with yours")
 71            }
 72        }
 73        .onChange(of: selectedFile) { old, path in
 74            guard let path, path != session.path else { return }
 75            if UnsavedChanges.resolve(session) {
 76                session.open(path)
 77            } else {
 78                selectedFile = old
 79            }
 80        }
 81        .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
 82        .onChange(of: options, initial: true) { _, options in session.options = options }
 83        .onChange(of: preset, initial: true) { loadKeymap() }
 84        .sheet(isPresented: $commands.showingPalette) {
 85            PaletteView(keymap: keymap) { id in
 86                commands.showingPalette = false
 87                // After the sheet closes, so app commands can present their own.
 88                DispatchQueue.main.async { perform(id) }
 89            }
 90        }
 91        .onChange(of: session.conflict) { _, conflict in
 92            if conflict != nil { commands.showingConflict = true }
 93        }
 94        .alert("Conflicting changes", isPresented: $commands.showingConflict) {
 95            Button("Keep Mine") { session.keepMine() }
 96            Button("Use Disk Version") { session.useDiskVersion() }
 97            Button("Decide Later", role: .cancel) {}
 98        } message: {
 99            Text((session.conflict ?? "") + " The version you don't keep is saved in the recovery folder.")
100        }
101        .onChange(of: workspace.changedFile?.version) {
102            if let path = workspace.changedFile?.path { session.fileChanged(path) }
103        }
104        .onChange(of: commands.focusSearch) { _, focus in
105            if focus {
106                searchFocused = true
107                commands.focusSearch = false
108            }
109        }
110        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
111            guard case .success(let url) = result else { return }
112            Task {
113                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
114            }
115        }
116        .sheet(isPresented: $commands.showingQuickOpen) {
117            QuickOpenView(workspace: workspace) { entry in
118                selectedFile = entry.path
119                commands.showingQuickOpen = false
120            }
121        }
122        .alert("Orgstar", isPresented: errorShown) {
123            Button("OK") {
124                workspace.lastError = nil
125                session.lastError = nil
126            }
127        } message: {
128            Text(workspace.lastError ?? session.lastError ?? "")
129        }
130        .task {
131            DevelopmentHooks.scheduleSnapshot()
132            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
133            await workspace.refresh()
134            workspace.startWatching()
135        }
136    }
137
138    private func loadKeymap() {
139        let loaded = KeymapLoader.load(preset)
140        keymap = loaded.keymap
141        if let first = loaded.problems.first {
142            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
143            commands.show("keymap.toml: \(first)\(more)")
144        }
145    }
146
147    /// Runs a command from a key, the palette or the Org menu.
148    private func perform(_ id: String) {
149        switch id {
150        case "app.save":
151            if !session.save(), session.conflict != nil { commands.showingConflict = true }
152        case "app.quick-open": commands.showingQuickOpen = true
153        case "app.palette": commands.showingPalette = true
154        case "app.search": commands.focusSearch = true
155        case "app.reload-keymap":
156            loadKeymap()
157            commands.show("Keymap reloaded")
158        case "app.refile":
159            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
160            commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
161                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
162                if let message = session.refile(to: target) { commands.show(message) }
163            }
164        case "app.archive":
165            if let message = session.archive() { commands.show(message) }
166        default:
167            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
168        }
169    }
170
171    private var errorShown: Binding<Bool> {
172        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
173    }
174}
175
176struct Sidebar: View {
177    let workspace: WorkspaceModel
178    @Binding var selection: String?
179
180    var body: some View {
181        List(selection: $selection) {
182            ForEach(workspace.rootPaths, id: \.self) { root in
183                Section((root as NSString).lastPathComponent) {
184                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
185                        Label(node.name, systemImage: icon(node))
186                            .foregroundStyle(node.file?.kind == .conflict ? .orange : .primary)
187                            .tag(node.file?.path)
188                    }
189                }
190                .contextMenu {
191                    Button("Remove Folder") { try? workspace.removeRoot(path: root) }
192                }
193            }
194        }
195        .listStyle(.sidebar)
196    }
197
198    private func icon(_ node: FileTreeNode) -> String {
199        guard let file = node.file else { return "folder" }
200        switch file.kind {
201        case .org: return "doc.text"
202        case .archive: return "archivebox"
203        case .conflict: return "exclamationmark.triangle"
204        }
205    }
206}
207
208struct OutlineColumn: View {
209    let session: DocumentSession
210
211    var body: some View {
212        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
213            Button {
214                session.reveal(entry.start)
215            } label: {
216                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
217                    .lineLimit(1)
218                    .padding(.leading, CGFloat(entry.level - 1) * 12)
219            }
220            .buttonStyle(.plain)
221        }
222        .overlay {
223            if session.path != nil, session.outline.isEmpty {
224                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
225            }
226        }
227    }
228}
229
230struct SearchResults: View {
231    let results: [HeadingLocation]
232    let open: (HeadingLocation) -> Void
233
234    var body: some View {
235        List(results, id: \.self) { location in
236            Button {
237                open(location)
238            } label: {
239                VStack(alignment: .leading, spacing: 2) {
240                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
241                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
242                }
243            }
244            .buttonStyle(.plain)
245        }
246        .overlay {
247            if results.isEmpty { ContentUnavailableView.search }
248        }
249    }
250}
251
252struct QuickOpenView: View {
253    let workspace: WorkspaceModel
254    let open: (FileEntry) -> Void
255    @State private var query = ""
256    @Environment(\.dismiss) private var dismiss
257
258    var body: some View {
259        let matches = workspace.quickOpen(query)
260        VStack(spacing: 0) {
261            TextField("Open file", text: $query)
262                .textFieldStyle(.plain)
263                .font(.title3)
264                .padding(12)
265                .onSubmit { if let first = matches.first { open(first) } }
266            Divider()
267            List(matches) { entry in
268                Button {
269                    open(entry)
270                } label: {
271                    VStack(alignment: .leading, spacing: 2) {
272                        Text(entry.name)
273                        Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
274                    }
275                }
276                .buttonStyle(.plain)
277            }
278        }
279        .frame(width: 520, height: 360)
280        .onExitCommand { dismiss() }
281    }
282}