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