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